Skip to content

Commit 8b99a89

Browse files
committed
Improved java
1 parent 139ea57 commit 8b99a89

File tree

103 files changed

+3557
-1575
lines changed

Some content is hidden

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

103 files changed

+3557
-1575
lines changed

src/main/java/g0001_0100/s0001_two_sum/readme.md

Lines changed: 52 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,23 +40,64 @@ You can return the answer in any order.
4040

4141
**Follow-up:** Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code> time complexity?
4242

43-
## Solution
43+
To solve the Two Sum problem in Java using a `Solution` class, we'll follow these steps:
44+
45+
1. Define a `Solution` class with a method named `twoSum`.
46+
2. Inside the `twoSum` method, create a hashmap to store elements and their indices.
47+
3. Iterate through the array:
48+
- For each element, calculate the complement required to reach the target sum.
49+
- Check if the complement exists in the hashmap.
50+
- If found, return the indices of the current element and the complement.
51+
- If not found, add the current element and its index to the hashmap.
52+
4. Handle edge cases:
53+
- If no solution is found, return an empty array or null (depending on the problem requirements).
54+
55+
Here's the implementation:
4456

4557
```java
4658
import java.util.HashMap;
47-
import java.util.Map;
4859

4960
public class Solution {
50-
public int[] twoSum(int[] numbers, int target) {
51-
Map<Integer, Integer> indexMap = new HashMap<>();
52-
for (int i = 0; i < numbers.length; i++) {
53-
Integer requiredNum = target - numbers[i];
54-
if (indexMap.containsKey(requiredNum)) {
55-
return new int[] {indexMap.get(requiredNum), i};
61+
62+
public int[] twoSum(int[] nums, int target) {
63+
// Create a hashmap to store elements and their indices
64+
HashMap<Integer, Integer> map = new HashMap<>();
65+
66+
// Iterate through the array
67+
for (int i = 0; i < nums.length; i++) {
68+
int complement = target - nums[i];
69+
// Check if the complement exists in the hashmap
70+
if (map.containsKey(complement)) {
71+
// Return the indices of the current element and the complement
72+
return new int[]{map.get(complement), i};
5673
}
57-
indexMap.put(numbers[i], i);
74+
// Add the current element and its index to the hashmap
75+
map.put(nums[i], i);
5876
}
59-
return new int[] {-1, -1};
77+
// If no solution is found, return an empty array or null
78+
return new int[]{};
79+
}
80+
81+
public static void main(String[] args) {
82+
Solution solution = new Solution();
83+
84+
// Test cases
85+
int[] nums1 = {2, 7, 11, 15};
86+
int target1 = 9;
87+
int[] result1 = solution.twoSum(nums1, target1);
88+
System.out.println("Example 1 Output: [" + result1[0] + ", " + result1[1] + "]");
89+
90+
int[] nums2 = {3, 2, 4};
91+
int target2 = 6;
92+
int[] result2 = solution.twoSum(nums2, target2);
93+
System.out.println("Example 2 Output: [" + result2[0] + ", " + result2[1] + "]");
94+
95+
int[] nums3 = {3, 3};
96+
int target3 = 6;
97+
int[] result3 = solution.twoSum(nums3, target3);
98+
System.out.println("Example 3 Output: [" + result3[0] + ", " + result3[1] + "]");
6099
}
61100
}
62-
```
101+
```
102+
103+
This implementation provides a solution to the Two Sum problem with a time complexity of O(n), where n is the number of elements in the input array.

src/main/java/g0001_0100/s0002_add_two_numbers/readme.md

Lines changed: 82 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -37,44 +37,100 @@ You may assume the two numbers do not contain any leading zero, except the numbe
3737
* `0 <= Node.val <= 9`
3838
* It is guaranteed that the list represents a number that does not have leading zeros.
3939

40-
## Solution
40+
To solve the Add Two Numbers problem in Java using a `Solution` class, we'll follow these steps:
41+
42+
1. Define a `ListNode` class to represent nodes in a linked list.
43+
2. Define a `Solution` class with a method named `addTwoNumbers`.
44+
3. Inside the `addTwoNumbers` method, traverse both input linked lists simultaneously:
45+
- Keep track of a carry variable to handle cases where the sum of two digits exceeds 9.
46+
- Calculate the sum of the current nodes' values along with the carry.
47+
- Update the carry for the next iteration.
48+
- Create a new node with the sum % 10 and attach it to the result linked list.
49+
- Move to the next nodes in both input lists.
50+
4. After finishing the traversal, check if there is any remaining carry. If so, add a new node with the carry to the result.
51+
5. Return the head of the result linked list.
52+
53+
Here's the implementation:
4154

4255
```java
43-
import com_github_leetcode.ListNode;
44-
45-
/*
46-
* Definition for singly-linked list.
47-
* public class ListNode {
48-
* int val;
49-
* ListNode next;
50-
* ListNode(int x) { val = x; }
51-
* }
52-
*/
56+
class ListNode {
57+
int val;
58+
ListNode next;
59+
60+
ListNode() {}
61+
62+
ListNode(int val) {
63+
this.val = val;
64+
}
65+
66+
ListNode(int val, ListNode next) {
67+
this.val = val;
68+
this.next = next;
69+
}
70+
}
71+
5372
public class Solution {
73+
5474
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
55-
ListNode dummyHead = new ListNode(0);
56-
ListNode p = l1;
57-
ListNode q = l2;
75+
ListNode dummyHead = new ListNode();
5876
ListNode curr = dummyHead;
5977
int carry = 0;
60-
while (p != null || q != null) {
61-
int x = (p != null) ? p.val : 0;
62-
int y = (q != null) ? q.val : 0;
63-
int sum = carry + x + y;
64-
carry = sum / 10;
65-
curr.next = new ListNode(sum % 10);
66-
curr = curr.next;
67-
if (p != null) {
68-
p = p.next;
78+
79+
while (l1 != null || l2 != null) {
80+
int sum = carry;
81+
if (l1 != null) {
82+
sum += l1.val;
83+
l1 = l1.next;
6984
}
70-
if (q != null) {
71-
q = q.next;
85+
if (l2 != null) {
86+
sum += l2.val;
87+
l2 = l2.next;
7288
}
89+
curr.next = new ListNode(sum % 10);
90+
curr = curr.next;
91+
carry = sum / 10;
7392
}
93+
7494
if (carry > 0) {
7595
curr.next = new ListNode(carry);
7696
}
97+
7798
return dummyHead.next;
7899
}
100+
101+
// Helper method to print a linked list
102+
public void printList(ListNode head) {
103+
ListNode curr = head;
104+
while (curr != null) {
105+
System.out.print(curr.val + " ");
106+
curr = curr.next;
107+
}
108+
System.out.println();
109+
}
110+
111+
public static void main(String[] args) {
112+
Solution solution = new Solution();
113+
114+
// Test cases
115+
ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
116+
ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4)));
117+
ListNode result1 = solution.addTwoNumbers(l1, l2);
118+
System.out.print("Example 1 Output: ");
119+
solution.printList(result1);
120+
121+
ListNode l3 = new ListNode(0);
122+
ListNode l4 = new ListNode(0);
123+
ListNode result2 = solution.addTwoNumbers(l3, l4);
124+
System.out.print("Example 2 Output: ");
125+
solution.printList(result2);
126+
127+
ListNode l5 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))))));
128+
ListNode l6 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))));
129+
ListNode result3 = solution.addTwoNumbers(l5, l6);
130+
System.out.print("Example 3 Output: ");
131+
solution.printList(result3);
132+
}
79133
}
80-
```
134+
```
135+
136+
This implementation provides a solution to the Add Two Numbers problem using linked lists in Java.

src/main/java/g0001_0100/s0003_longest_substring_without_repeating_characters/readme.md

Lines changed: 52 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -42,34 +42,65 @@ Given a string `s`, find the length of the **longest substring** without repeati
4242
* <code>0 <= s.length <= 5 * 10<sup>4</sup></code>
4343
* `s` consists of English letters, digits, symbols and spaces.
4444

45-
## Solution
45+
To solve the Longest Substring Without Repeating Characters problem in Java using a `Solution` class, we'll follow these steps:
46+
47+
1. Define a `Solution` class with a method named `lengthOfLongestSubstring`.
48+
2. Initialize variables to keep track of the starting index of the substring (`start`), the maximum length (`maxLen`), and a hashmap to store characters and their indices.
49+
3. Iterate through the string `s`, and for each character:
50+
- Check if the character exists in the hashmap and its index is greater than or equal to the `start` index.
51+
- If found, update the `start` index to the index after the last occurrence of the character.
52+
- Update the maximum length if necessary.
53+
- Update the index of the current character in the hashmap.
54+
4. Return the maximum length found.
55+
5. Handle the edge case where the input string is empty.
56+
57+
Here's the implementation:
4658

4759
```java
60+
import java.util.HashMap;
61+
4862
public class Solution {
63+
4964
public int lengthOfLongestSubstring(String s) {
50-
int[] lastIndices = new int[256];
51-
for (int i = 0; i < 256; i++) {
52-
lastIndices[i] = -1;
53-
}
54-
int maxLen = 0;
55-
int curLen = 0;
65+
// Initialize variables
5666
int start = 0;
57-
for (int i = 0; i < s.length(); i++) {
58-
char cur = s.charAt(i);
59-
if (lastIndices[cur] < start) {
60-
lastIndices[cur] = i;
61-
curLen++;
62-
} else {
63-
int lastIndex = lastIndices[cur];
64-
start = lastIndex + 1;
65-
curLen = i - start + 1;
66-
lastIndices[cur] = i;
67-
}
68-
if (curLen > maxLen) {
69-
maxLen = curLen;
67+
int maxLen = 0;
68+
HashMap<Character, Integer> map = new HashMap<>();
69+
70+
// Iterate through the string
71+
for (int end = 0; end < s.length(); end++) {
72+
char ch = s.charAt(end);
73+
// If the character exists in the hashmap and its index is greater than or equal to the start index
74+
if (map.containsKey(ch) && map.get(ch) >= start) {
75+
// Update the start index to the index after the last occurrence of the character
76+
start = map.get(ch) + 1;
7077
}
78+
// Update the maximum length if necessary
79+
maxLen = Math.max(maxLen, end - start + 1);
80+
// Update the index of the current character in the hashmap
81+
map.put(ch, end);
7182
}
83+
7284
return maxLen;
7385
}
86+
87+
public static void main(String[] args) {
88+
Solution solution = new Solution();
89+
90+
// Test cases
91+
String s1 = "abcabcbb";
92+
System.out.println("Example 1 Output: " + solution.lengthOfLongestSubstring(s1));
93+
94+
String s2 = "bbbbb";
95+
System.out.println("Example 2 Output: " + solution.lengthOfLongestSubstring(s2));
96+
97+
String s3 = "pwwkew";
98+
System.out.println("Example 3 Output: " + solution.lengthOfLongestSubstring(s3));
99+
100+
String s4 = "";
101+
System.out.println("Example 4 Output: " + solution.lengthOfLongestSubstring(s4));
102+
}
74103
}
75-
```
104+
```
105+
106+
This implementation provides a solution to the Longest Substring Without Repeating Characters problem in Java.

src/main/java/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md

Lines changed: 60 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -52,40 +52,70 @@ The overall run time complexity should be `O(log (m+n))`.
5252
* `1 <= m + n <= 2000`
5353
* <code>-10<sup>6</sup> <= nums1[i], nums2[i] <= 10<sup>6</sup></code>
5454

55-
## Solution
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:
5666

5767
```java
58-
@SuppressWarnings("java:S2234")
5968
public class Solution {
69+
6070
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
61-
if (nums2.length < nums1.length) {
62-
return findMedianSortedArrays(nums2, nums1);
63-
}
64-
int cut1;
65-
int cut2;
66-
int n1 = nums1.length;
67-
int n2 = nums2.length;
68-
int low = 0;
69-
int high = n1;
70-
while (low <= high) {
71-
cut1 = (low + high) / 2;
72-
cut2 = ((n1 + n2 + 1) / 2) - cut1;
73-
int l1 = cut1 == 0 ? Integer.MIN_VALUE : nums1[cut1 - 1];
74-
int l2 = cut2 == 0 ? Integer.MIN_VALUE : nums2[cut2 - 1];
75-
int r1 = cut1 == n1 ? Integer.MAX_VALUE : nums1[cut1];
76-
int r2 = cut2 == n2 ? Integer.MAX_VALUE : nums2[cut2];
77-
if (l1 <= r2 && l2 <= r1) {
78-
if ((n1 + n2) % 2 == 0) {
79-
return (Math.max(l1, l2) + Math.min(r1, r2)) / 2.0;
80-
}
81-
return Math.max(l1, l2);
82-
} else if (l1 > r2) {
83-
high = cut1 - 1;
84-
} else {
85-
low = cut1 + 1;
86-
}
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);
8791
}
88-
return 0.0f;
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));
89117
}
90118
}
91-
```
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)