Skip to content

Added Cpp #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
614 changes: 307 additions & 307 deletions README.md

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions src/main/cpp/g0001_0100/s0001_two_sum/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Array #Hash_Table
// #Data_Structure_I_Day_2_Array #Level_1_Day_13_Hashmap #Udemy_Arrays #Big_O_Time_O(n)_Space_O(n)
// #2024_05_12_Time_4_ms_(94.42%)_Space_14.1_MB_(17.14%)

#include <vector>
#include <unordered_map>

class Solution {
public:
std::vector<int> twoSum(std::vector<int>& numbers, int target) {
std::unordered_map<int, int> indexMap;
for (int i = 0; i < numbers.size(); i++) {
int requiredNum = target - numbers[i];
if (indexMap.find(requiredNum) != indexMap.end()) {
return {indexMap[requiredNum], i};
}
indexMap[numbers[i]] = i;
}
return {-1, -1};
}
};
38 changes: 38 additions & 0 deletions src/main/cpp/g0001_0100/s0001_two_sum/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
1\. Two Sum

Easy

Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.

You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.

You can return the answer in any order.

**Example 1:**

**Input:** nums = [2,7,11,15], target = 9

**Output:** [0,1]

**Explanation:** Because nums[0] + nums[1] == 9, we return [0, 1].

**Example 2:**

**Input:** nums = [3,2,4], target = 6

**Output:** [1,2]

**Example 3:**

**Input:** nums = [3,3], target = 6

**Output:** [0,1]

**Constraints:**

* <code>2 <= nums.length <= 10<sup>4</sup></code>
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
* <code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code>
* **Only one valid answer exists.**

**Follow-up:** Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code> time complexity?
42 changes: 42 additions & 0 deletions src/main/cpp/g0001_0100/s0002_add_two_numbers/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Math #Linked_List #Recursion
// #Data_Structure_II_Day_10_Linked_List #Programming_Skills_II_Day_15
// #Big_O_Time_O(max(N,M))_Space_O(max(N,M)) #2024_05_12_Time_16_ms_(82.17%)_Space_76.1_MB_(52.68%)

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummyHead = new ListNode(0);
ListNode* p = l1;
ListNode* q = l2;
ListNode* curr = dummyHead;
int carry = 0;
while (p != nullptr || q != nullptr) {
int x = (p != nullptr) ? p->val : 0;
int y = (q != nullptr) ? q->val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr->next = new ListNode(sum % 10);
curr = curr->next;
if (p != nullptr) {
p = p->next;
}
if (q != nullptr) {
q = q->next;
}
}
if (carry > 0) {
curr->next = new ListNode(carry);
}
return dummyHead->next;
}
};
35 changes: 35 additions & 0 deletions src/main/cpp/g0001_0100/s0002_add_two_numbers/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
2\. Add Two Numbers

Medium

You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg)

**Input:** l1 = [2,4,3], l2 = [5,6,4]

**Output:** [7,0,8]

**Explanation:** 342 + 465 = 807.

**Example 2:**

**Input:** l1 = [0], l2 = [0]

**Output:** [0]

**Example 3:**

**Input:** l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]

**Output:** [8,9,9,9,0,0,0,1]

**Constraints:**

* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Hash_Table #Sliding_Window
// #Algorithm_I_Day_6_Sliding_Window #Level_2_Day_14_Sliding_Window/Two_Pointer #Udemy_Strings
// #Big_O_Time_O(n)_Space_O(1) #2024_05_12_Time_5_ms_(86.87%)_Space_10.4_MB_(74.49%)

#include <string>
#include <vector>
#include <algorithm>

class Solution {
public:
int lengthOfLongestSubstring(std::string s) {
std::vector<int> lastIndices(256, -1);
int maxLen = 0;
int curLen = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
char cur = s[i];
if (lastIndices[cur] < start) {
lastIndices[cur] = i;
curLen++;
} else {
int lastIndex = lastIndices[cur];
start = lastIndex + 1;
curLen = i - start + 1;
lastIndices[cur] = i;
}
maxLen = std::max(maxLen, curLen);
}
return maxLen;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
3\. Longest Substring Without Repeating Characters

Medium

Given a string `s`, find the length of the **longest substring** without repeating characters.

**Example 1:**

**Input:** s = "abcabcbb"

**Output:** 3

**Explanation:** The answer is "abc", with the length of 3.

**Example 2:**

**Input:** s = "bbbbb"

**Output:** 1

**Explanation:** The answer is "b", with the length of 1.

**Example 3:**

**Input:** s = "pwwkew"

**Output:** 3

**Explanation:** The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

**Example 4:**

**Input:** s = ""

**Output:** 0

**Constraints:**

* <code>0 <= s.length <= 5 * 10<sup>4</sup></code>
* `s` consists of English letters, digits, symbols and spaces.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// #Hard #Top_100_Liked_Questions #Top_Interview_Questions #Array #Binary_Search #Divide_and_Conquer
// #Big_O_Time_O(log(min(N,M)))_Space_O(1) #2024_05_22_Time_19_ms_(85.75%)_Space_94.4_MB_(74.87%)

#include <vector>
#include <algorithm>
#include <climits>

class Solution {
public:
double findMedianSortedArrays(std::vector<int>& nums1, std::vector<int>& nums2) {
if (nums2.size() < nums1.size()) {
return findMedianSortedArrays(nums2, nums1);
}

int n1 = nums1.size();
int n2 = nums2.size();
int low = 0;
int high = n1;

while (low <= high) {
int cut1 = (low + high) / 2;
int cut2 = (n1 + n2 + 1) / 2 - cut1;

int l1 = (cut1 == 0) ? INT_MIN : nums1[cut1 - 1];
int l2 = (cut2 == 0) ? INT_MIN : nums2[cut2 - 1];
int r1 = (cut1 == n1) ? INT_MAX : nums1[cut1];
int r2 = (cut2 == n2) ? INT_MAX : nums2[cut2];

if (l1 <= r2 && l2 <= r1) {
if ((n1 + n2) % 2 == 0) {
return (std::max(l1, l2) + std::min(r1, r2)) / 2.0;
}
return std::max(l1, l2);
} else if (l1 > r2) {
high = cut1 - 1;
} else {
low = cut1 + 1;
}
}

return 0.0;
}
};
118 changes: 118 additions & 0 deletions src/main/cpp/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
4\. Median of Two Sorted Arrays

Hard

Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.

The overall run time complexity should be `O(log (m+n))`.

**Example 1:**

**Input:** nums1 = [1,3], nums2 = [2]

**Output:** 2.00000

**Explanation:** merged array = [1,2,3] and median is 2.

**Example 2:**

**Input:** nums1 = [1,2], nums2 = [3,4]

**Output:** 2.50000

**Explanation:** merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

**Example 3:**

**Input:** nums1 = [0,0], nums2 = [0,0]

**Output:** 0.00000

**Example 4:**

**Input:** nums1 = [], nums2 = [1]

**Output:** 1.00000

**Example 5:**

**Input:** nums1 = [2], nums2 = []

**Output:** 2.00000

**Constraints:**

* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* <code>-10<sup>6</sup> <= nums1[i], nums2[i] <= 10<sup>6</sup></code>

To solve the Median of Two Sorted Arrays problem in Java using a `Solution` class, we'll follow these steps:

1. Define a `Solution` class with a method named `findMedianSortedArrays`.
2. Calculate the total length of the combined array (m + n).
3. Determine the middle index or indices of the combined array based on its length (for both even and odd lengths).
4. Implement a binary search algorithm to find the correct position for partitioning the two arrays such that elements to the left are less than or equal to elements on the right.
5. Calculate the median based on the partitioned arrays.
6. Handle edge cases where one or both arrays are empty or where the combined length is odd or even.
7. Return the calculated median.

Here's the implementation:

```java
public class Solution {

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int totalLength = m + n;
int left = (totalLength + 1) / 2;
int right = (totalLength + 2) / 2;
return (findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0;
}

private int findKth(int[] nums1, int i, int[] nums2, int j, int k) {
if (i >= nums1.length) return nums2[j + k - 1];
if (j >= nums2.length) return nums1[i + k - 1];
if (k == 1) return Math.min(nums1[i], nums2[j]);

int midVal1 = (i + k / 2 - 1 < nums1.length) ? nums1[i + k / 2 - 1] : Integer.MAX_VALUE;
int midVal2 = (j + k / 2 - 1 < nums2.length) ? nums2[j + k / 2 - 1] : Integer.MAX_VALUE;

if (midVal1 < midVal2) {
return findKth(nums1, i + k / 2, nums2, j, k - k / 2);
} else {
return findKth(nums1, i, nums2, j + k / 2, k - k / 2);
}
}

public static void main(String[] args) {
Solution solution = new Solution();

// Test cases
int[] nums1_1 = {1, 3};
int[] nums2_1 = {2};
System.out.println("Example 1 Output: " + solution.findMedianSortedArrays(nums1_1, nums2_1));

int[] nums1_2 = {1, 2};
int[] nums2_2 = {3, 4};
System.out.println("Example 2 Output: " + solution.findMedianSortedArrays(nums1_2, nums2_2));

int[] nums1_3 = {0, 0};
int[] nums2_3 = {0, 0};
System.out.println("Example 3 Output: " + solution.findMedianSortedArrays(nums1_3, nums2_3));

int[] nums1_4 = {};
int[] nums2_4 = {1};
System.out.println("Example 4 Output: " + solution.findMedianSortedArrays(nums1_4, nums2_4));

int[] nums1_5 = {2};
int[] nums2_5 = {};
System.out.println("Example 5 Output: " + solution.findMedianSortedArrays(nums1_5, nums2_5));
}
}
```

This implementation provides a solution to the Median of Two Sorted Arrays problem in Java with a runtime complexity of O(log(min(m, n))).
Loading
Loading