Skip to content

Commit 57f259f

Browse files
committed
Added Cpp
1 parent 8b99a89 commit 57f259f

File tree

84 files changed

+7460
-410
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

84 files changed

+7460
-410
lines changed

README.md

+410-410
Large diffs are not rendered by default.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 1\. Two Sum
5+
6+
Easy
7+
8+
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
9+
10+
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
11+
12+
You can return the answer in any order.
13+
14+
**Example 1:**
15+
16+
**Input:** nums = [2,7,11,15], target = 9
17+
18+
**Output:** [0,1]
19+
20+
**Explanation:** Because nums[0] + nums[1] == 9, we return [0, 1].
21+
22+
**Example 2:**
23+
24+
**Input:** nums = [3,2,4], target = 6
25+
26+
**Output:** [1,2]
27+
28+
**Example 3:**
29+
30+
**Input:** nums = [3,3], target = 6
31+
32+
**Output:** [0,1]
33+
34+
**Constraints:**
35+
36+
* <code>2 <= nums.length <= 10<sup>4</sup></code>
37+
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
38+
* <code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code>
39+
* **Only one valid answer exists.**
40+
41+
**Follow-up:** Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code> time complexity?
42+
43+
## Solution
44+
45+
```cpp
46+
#include <vector>
47+
#include <unordered_map>
48+
49+
class Solution {
50+
public:
51+
std::vector<int> twoSum(std::vector<int>& numbers, int target) {
52+
std::unordered_map<int, int> indexMap;
53+
for (int i = 0; i < numbers.size(); i++) {
54+
int requiredNum = target - numbers[i];
55+
if (indexMap.find(requiredNum) != indexMap.end()) {
56+
return {indexMap[requiredNum], i};
57+
}
58+
indexMap[numbers[i]] = i;
59+
}
60+
return {-1, -1};
61+
}
62+
};
63+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 2\. Add Two Numbers
5+
6+
Medium
7+
8+
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.
9+
10+
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
11+
12+
**Example 1:**
13+
14+
![](https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg)
15+
16+
**Input:** l1 = [2,4,3], l2 = [5,6,4]
17+
18+
**Output:** [7,0,8]
19+
20+
**Explanation:** 342 + 465 = 807.
21+
22+
**Example 2:**
23+
24+
**Input:** l1 = [0], l2 = [0]
25+
26+
**Output:** [0]
27+
28+
**Example 3:**
29+
30+
**Input:** l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
31+
32+
**Output:** [8,9,9,9,0,0,0,1]
33+
34+
**Constraints:**
35+
36+
* The number of nodes in each linked list is in the range `[1, 100]`.
37+
* `0 <= Node.val <= 9`
38+
* It is guaranteed that the list represents a number that does not have leading zeros.
39+
40+
## Solution
41+
42+
```cpp
43+
/**
44+
* Definition for singly-linked list.
45+
* struct ListNode {
46+
* int val;
47+
* ListNode *next;
48+
* ListNode() : val(0), next(nullptr) {}
49+
* ListNode(int x) : val(x), next(nullptr) {}
50+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
51+
* };
52+
*/
53+
class Solution {
54+
public:
55+
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
56+
ListNode* dummyHead = new ListNode(0);
57+
ListNode* p = l1;
58+
ListNode* q = l2;
59+
ListNode* curr = dummyHead;
60+
int carry = 0;
61+
while (p != nullptr || q != nullptr) {
62+
int x = (p != nullptr) ? p->val : 0;
63+
int y = (q != nullptr) ? q->val : 0;
64+
int sum = carry + x + y;
65+
carry = sum / 10;
66+
curr->next = new ListNode(sum % 10);
67+
curr = curr->next;
68+
if (p != nullptr) {
69+
p = p->next;
70+
}
71+
if (q != nullptr) {
72+
q = q->next;
73+
}
74+
}
75+
if (carry > 0) {
76+
curr->next = new ListNode(carry);
77+
}
78+
return dummyHead->next;
79+
}
80+
};
81+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 3\. Longest Substring Without Repeating Characters
5+
6+
Medium
7+
8+
Given a string `s`, find the length of the **longest substring** without repeating characters.
9+
10+
**Example 1:**
11+
12+
**Input:** s = "abcabcbb"
13+
14+
**Output:** 3
15+
16+
**Explanation:** The answer is "abc", with the length of 3.
17+
18+
**Example 2:**
19+
20+
**Input:** s = "bbbbb"
21+
22+
**Output:** 1
23+
24+
**Explanation:** The answer is "b", with the length of 1.
25+
26+
**Example 3:**
27+
28+
**Input:** s = "pwwkew"
29+
30+
**Output:** 3
31+
32+
**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.
33+
34+
**Example 4:**
35+
36+
**Input:** s = ""
37+
38+
**Output:** 0
39+
40+
**Constraints:**
41+
42+
* <code>0 <= s.length <= 5 * 10<sup>4</sup></code>
43+
* `s` consists of English letters, digits, symbols and spaces.
44+
45+
## Solution
46+
47+
```cpp
48+
#include <string>
49+
#include <vector>
50+
#include <algorithm>
51+
52+
class Solution {
53+
public:
54+
int lengthOfLongestSubstring(std::string s) {
55+
std::vector<int> lastIndices(256, -1);
56+
int maxLen = 0;
57+
int curLen = 0;
58+
int start = 0;
59+
for (int i = 0; i < s.length(); i++) {
60+
char cur = s[i];
61+
if (lastIndices[cur] < start) {
62+
lastIndices[cur] = i;
63+
curLen++;
64+
} else {
65+
int lastIndex = lastIndices[cur];
66+
start = lastIndex + 1;
67+
curLen = i - start + 1;
68+
lastIndices[cur] = i;
69+
}
70+
maxLen = std::max(maxLen, curLen);
71+
}
72+
return maxLen;
73+
}
74+
};
75+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 4\. Median of Two Sorted Arrays
5+
6+
Hard
7+
8+
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
9+
10+
The overall run time complexity should be `O(log (m+n))`.
11+
12+
**Example 1:**
13+
14+
**Input:** nums1 = [1,3], nums2 = [2]
15+
16+
**Output:** 2.00000
17+
18+
**Explanation:** merged array = [1,2,3] and median is 2.
19+
20+
**Example 2:**
21+
22+
**Input:** nums1 = [1,2], nums2 = [3,4]
23+
24+
**Output:** 2.50000
25+
26+
**Explanation:** merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
27+
28+
**Example 3:**
29+
30+
**Input:** nums1 = [0,0], nums2 = [0,0]
31+
32+
**Output:** 0.00000
33+
34+
**Example 4:**
35+
36+
**Input:** nums1 = [], nums2 = [1]
37+
38+
**Output:** 1.00000
39+
40+
**Example 5:**
41+
42+
**Input:** nums1 = [2], nums2 = []
43+
44+
**Output:** 2.00000
45+
46+
**Constraints:**
47+
48+
* `nums1.length == m`
49+
* `nums2.length == n`
50+
* `0 <= m <= 1000`
51+
* `0 <= n <= 1000`
52+
* `1 <= m + n <= 2000`
53+
* <code>-10<sup>6</sup> <= nums1[i], nums2[i] <= 10<sup>6</sup></code>
54+
55+
To solve the Median of Two Sorted Arrays problem in Java using a `Solution` class, we'll follow these steps:
56+
57+
1. Define a `Solution` class with a method named `findMedianSortedArrays`.
58+
2. Calculate the total length of the combined array (m + n).
59+
3. Determine the middle index or indices of the combined array based on its length (for both even and odd lengths).
60+
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.
61+
5. Calculate the median based on the partitioned arrays.
62+
6. Handle edge cases where one or both arrays are empty or where the combined length is odd or even.
63+
7. Return the calculated median.
64+
65+
Here's the implementation:
66+
67+
```java
68+
public class Solution {
69+
70+
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
71+
int m = nums1.length;
72+
int n = nums2.length;
73+
int totalLength = m + n;
74+
int left = (totalLength + 1) / 2;
75+
int right = (totalLength + 2) / 2;
76+
return (findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0;
77+
}
78+
79+
private int findKth(int[] nums1, int i, int[] nums2, int j, int k) {
80+
if (i >= nums1.length) return nums2[j + k - 1];
81+
if (j >= nums2.length) return nums1[i + k - 1];
82+
if (k == 1) return Math.min(nums1[i], nums2[j]);
83+
84+
int midVal1 = (i + k / 2 - 1 < nums1.length) ? nums1[i + k / 2 - 1] : Integer.MAX_VALUE;
85+
int midVal2 = (j + k / 2 - 1 < nums2.length) ? nums2[j + k / 2 - 1] : Integer.MAX_VALUE;
86+
87+
if (midVal1 < midVal2) {
88+
return findKth(nums1, i + k / 2, nums2, j, k - k / 2);
89+
} else {
90+
return findKth(nums1, i, nums2, j + k / 2, k - k / 2);
91+
}
92+
}
93+
94+
public static void main(String[] args) {
95+
Solution solution = new Solution();
96+
97+
// Test cases
98+
int[] nums1_1 = {1, 3};
99+
int[] nums2_1 = {2};
100+
System.out.println("Example 1 Output: " + solution.findMedianSortedArrays(nums1_1, nums2_1));
101+
102+
int[] nums1_2 = {1, 2};
103+
int[] nums2_2 = {3, 4};
104+
System.out.println("Example 2 Output: " + solution.findMedianSortedArrays(nums1_2, nums2_2));
105+
106+
int[] nums1_3 = {0, 0};
107+
int[] nums2_3 = {0, 0};
108+
System.out.println("Example 3 Output: " + solution.findMedianSortedArrays(nums1_3, nums2_3));
109+
110+
int[] nums1_4 = {};
111+
int[] nums2_4 = {1};
112+
System.out.println("Example 4 Output: " + solution.findMedianSortedArrays(nums1_4, nums2_4));
113+
114+
int[] nums1_5 = {2};
115+
int[] nums2_5 = {};
116+
System.out.println("Example 5 Output: " + solution.findMedianSortedArrays(nums1_5, nums2_5));
117+
}
118+
}
119+
```
120+
121+
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))).

0 commit comments

Comments
 (0)