Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd39a9c4

Browse files
authored
Added tasks 4-15
1 parentc5e22d7 commitd39a9c4

File tree

10 files changed

+730
-0
lines changed

10 files changed

+730
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// #Hard #Top_100_Liked_Questions #Top_Interview_Questions #Array #Binary_Search #Divide_and_Conquer
2+
// #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%)
3+
4+
#include<vector>
5+
#include<algorithm>
6+
#include<climits>
7+
8+
classSolution {
9+
public:
10+
doublefindMedianSortedArrays(std::vector<int>& nums1, std::vector<int>& nums2) {
11+
if (nums2.size() < nums1.size()) {
12+
returnfindMedianSortedArrays(nums2, nums1);
13+
}
14+
15+
int n1 = nums1.size();
16+
int n2 = nums2.size();
17+
int low =0;
18+
int high = n1;
19+
20+
while (low <= high) {
21+
int cut1 = (low + high) /2;
22+
int cut2 = (n1 + n2 +1) /2 - cut1;
23+
24+
int l1 = (cut1 ==0) ? INT_MIN : nums1[cut1 -1];
25+
int l2 = (cut2 ==0) ? INT_MIN : nums2[cut2 -1];
26+
int r1 = (cut1 == n1) ? INT_MAX : nums1[cut1];
27+
int r2 = (cut2 == n2) ? INT_MAX : nums2[cut2];
28+
29+
if (l1 <= r2 && l2 <= r1) {
30+
if ((n1 + n2) %2 ==0) {
31+
return (std::max(l1, l2) +std::min(r1, r2)) /2.0;
32+
}
33+
returnstd::max(l1, l2);
34+
}elseif (l1 > r2) {
35+
high = cut1 -1;
36+
}else {
37+
low = cut1 +1;
38+
}
39+
}
40+
41+
return0.0;
42+
}
43+
};
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
4\. Median of Two Sorted Arrays
2+
3+
Hard
4+
5+
Given two sorted arrays`nums1` and`nums2` of size`m` and`n` respectively, return**the median** of the two sorted arrays.
6+
7+
The overall run time complexity should be`O(log (m+n))`.
8+
9+
**Example 1:**
10+
11+
**Input:** nums1 =[1,3], nums2 =[2]
12+
13+
**Output:** 2.00000
14+
15+
**Explanation:** merged array =[1,2,3] and median is 2.
16+
17+
**Example 2:**
18+
19+
**Input:** nums1 =[1,2], nums2 =[3,4]
20+
21+
**Output:** 2.50000
22+
23+
**Explanation:** merged array =[1,2,3,4] and median is (2 + 3) / 2 = 2.5.
24+
25+
**Example 3:**
26+
27+
**Input:** nums1 =[0,0], nums2 =[0,0]
28+
29+
**Output:** 0.00000
30+
31+
**Example 4:**
32+
33+
**Input:** nums1 =[], nums2 =[1]
34+
35+
**Output:** 1.00000
36+
37+
**Example 5:**
38+
39+
**Input:** nums1 =[2], nums2 =[]
40+
41+
**Output:** 2.00000
42+
43+
**Constraints:**
44+
45+
*`nums1.length == m`
46+
*`nums2.length == n`
47+
*`0 <= m <= 1000`
48+
*`0 <= n <= 1000`
49+
*`1 <= m + n <= 2000`
50+
* <code>-10<sup>6</sup> <= nums1[i], nums2[i] <= 10<sup>6</sup></code>
51+
52+
To solve the Median of Two Sorted Arrays problem in Java using a`Solution` class, we'll follow these steps:
53+
54+
1. Define a`Solution` class with a method named`findMedianSortedArrays`.
55+
2. Calculate the total length of the combined array (m + n).
56+
3. Determine the middle index or indices of the combined array based on its length (for both even and odd lengths).
57+
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.
58+
5. Calculate the median based on the partitioned arrays.
59+
6. Handle edge cases where one or both arrays are empty or where the combined length is odd or even.
60+
7. Return the calculated median.
61+
62+
Here's the implementation:
63+
64+
```java
65+
publicclassSolution {
66+
67+
publicdoublefindMedianSortedArrays(int[]nums1,int[]nums2) {
68+
int m= nums1.length;
69+
int n= nums2.length;
70+
int totalLength= m+ n;
71+
int left= (totalLength+1)/2;
72+
int right= (totalLength+2)/2;
73+
return (findKth(nums1,0, nums2,0, left)+ findKth(nums1,0, nums2,0, right))/2.0;
74+
}
75+
76+
privateintfindKth(int[]nums1,inti,int[]nums2,intj,intk) {
77+
if (i>= nums1.length)return nums2[j+ k-1];
78+
if (j>= nums2.length)return nums1[i+ k-1];
79+
if (k==1)returnMath.min(nums1[i], nums2[j]);
80+
81+
int midVal1= (i+ k/2-1< nums1.length)? nums1[i+ k/2-1]:Integer.MAX_VALUE;
82+
int midVal2= (j+ k/2-1< nums2.length)? nums2[j+ k/2-1]:Integer.MAX_VALUE;
83+
84+
if (midVal1< midVal2) {
85+
return findKth(nums1, i+ k/2, nums2, j, k- k/2);
86+
}else {
87+
return findKth(nums1, i, nums2, j+ k/2, k- k/2);
88+
}
89+
}
90+
91+
publicstaticvoidmain(String[]args) {
92+
Solution solution=newSolution();
93+
94+
// Test cases
95+
int[] nums1_1= {1,3};
96+
int[] nums2_1= {2};
97+
System.out.println("Example 1 Output:"+ solution.findMedianSortedArrays(nums1_1, nums2_1));
98+
99+
int[] nums1_2= {1,2};
100+
int[] nums2_2= {3,4};
101+
System.out.println("Example 2 Output:"+ solution.findMedianSortedArrays(nums1_2, nums2_2));
102+
103+
int[] nums1_3= {0,0};
104+
int[] nums2_3= {0,0};
105+
System.out.println("Example 3 Output:"+ solution.findMedianSortedArrays(nums1_3, nums2_3));
106+
107+
int[] nums1_4= {};
108+
int[] nums2_4= {1};
109+
System.out.println("Example 4 Output:"+ solution.findMedianSortedArrays(nums1_4, nums2_4));
110+
111+
int[] nums1_5= {2};
112+
int[] nums2_5= {};
113+
System.out.println("Example 5 Output:"+ solution.findMedianSortedArrays(nums1_5, nums2_5));
114+
}
115+
}
116+
```
117+
118+
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))).
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Dynamic_Programming
2+
// #Data_Structure_II_Day_9_String #Algorithm_II_Day_14_Dynamic_Programming
3+
// #Dynamic_Programming_I_Day_17 #Udemy_Strings #Big_O_Time_O(n)_Space_O(n)
4+
// #2024_05_22_Time_7_ms_(94.72%)_Space_9.2_MB_(70.29%)
5+
6+
#include<vector>
7+
#include<string>
8+
#include<algorithm>
9+
10+
classSolution {
11+
public:
12+
std::stringlongestPalindrome(const std::string& s) {
13+
// Transform s into newStr with delimiters
14+
std::stringnewStr(s.length() *2 +1,'#');
15+
for (int i =0; i < s.length(); ++i) {
16+
newStr[2 * i +1] = s[i];
17+
}
18+
19+
std::vector<int>dp(newStr.length(),0);
20+
int friendCenter =0, friendRadius =0;
21+
int lpsCenter =0, lpsRadius =0;
22+
23+
for (int i =0; i < newStr.length(); ++i) {
24+
dp[i] = (friendCenter + friendRadius > i)
25+
?std::min(dp[2 * friendCenter - i], friendCenter + friendRadius - i)
26+
:1;
27+
28+
while (i + dp[i] < newStr.length() && i - dp[i] >=0 && newStr[i + dp[i]] == newStr[i - dp[i]]) {
29+
dp[i]++;
30+
}
31+
32+
if (friendCenter + friendRadius < i + dp[i]) {
33+
friendCenter = i;
34+
friendRadius = dp[i];
35+
}
36+
37+
if (lpsRadius < dp[i]) {
38+
lpsCenter = i;
39+
lpsRadius = dp[i];
40+
}
41+
}
42+
43+
int start = (lpsCenter - lpsRadius +1) /2;
44+
int length = lpsRadius -1;
45+
return s.substr(start, length);
46+
}
47+
};
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
5\. Longest Palindromic Substring
2+
3+
Medium
4+
5+
Given a string`s`, return_the longest palindromic substring_ in`s`.
6+
7+
**Example 1:**
8+
9+
**Input:** s = "babad"
10+
11+
**Output:** "bab"**Note:** "aba" is also a valid answer.
12+
13+
**Example 2:**
14+
15+
**Input:** s = "cbbd"
16+
17+
**Output:** "bb"
18+
19+
**Example 3:**
20+
21+
**Input:** s = "a"
22+
23+
**Output:** "a"
24+
25+
**Example 4:**
26+
27+
**Input:** s = "ac"
28+
29+
**Output:** "a"
30+
31+
**Constraints:**
32+
33+
*`1 <= s.length <= 1000`
34+
*`s` consist of only digits and English letters.
35+
36+
To solve the Longest Palindromic Substring problem in Java using a`Solution` class, we'll follow these steps:
37+
38+
1. Define a`Solution` class with a method named`longestPalindrome`.
39+
2. Initialize variables to keep track of the start and end indices of the longest palindromic substring found so far (`start` and`end`).
40+
3. Iterate through the string`s`:
41+
- For each character in the string, expand around it to check if it forms a palindrome.
42+
- Handle both odd-length and even-length palindromes separately.
43+
- Update`start` and`end` indices if a longer palindrome is found.
44+
4. Return the substring from`start` to`end`.
45+
5. Handle edge cases where the input string is empty or has a length of 1.
46+
47+
Here's the implementation:
48+
49+
```java
50+
publicclassSolution {
51+
52+
publicStringlongestPalindrome(Strings) {
53+
if (s==null|| s.length()<1)return"";
54+
int start=0;
55+
int end=0;
56+
57+
for (int i=0; i< s.length(); i++) {
58+
int len1= expandAroundCenter(s, i, i);
59+
int len2= expandAroundCenter(s, i, i+1);
60+
int len=Math.max(len1, len2);
61+
if (len> end- start) {
62+
start= i- (len-1)/2;
63+
end= i+ len/2;
64+
}
65+
}
66+
67+
return s.substring(start, end+1);
68+
}
69+
70+
privateintexpandAroundCenter(Strings,intleft,intright) {
71+
while (left>=0&& right< s.length()&& s.charAt(left)== s.charAt(right)) {
72+
left--;
73+
right++;
74+
}
75+
return right- left-1;
76+
}
77+
78+
publicstaticvoidmain(String[]args) {
79+
Solution solution=newSolution();
80+
81+
// Test cases
82+
String s1="babad";
83+
System.out.println("Example 1 Output:"+ solution.longestPalindrome(s1));
84+
85+
String s2="cbbd";
86+
System.out.println("Example 2 Output:"+ solution.longestPalindrome(s2));
87+
88+
String s3="a";
89+
System.out.println("Example 3 Output:"+ solution.longestPalindrome(s3));
90+
91+
String s4="ac";
92+
System.out.println("Example 4 Output:"+ solution.longestPalindrome(s4));
93+
}
94+
}
95+
```
96+
97+
This implementation provides a solution to the Longest Palindromic Substring problem in Java.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// #Hard #Top_Interview_Questions #String #Dynamic_Programming #Recursion #Udemy_Dynamic_Programming
2+
// #Big_O_Time_O(m*n)_Space_O(m*n) #2024_05_22_Time_0_ms_(100.00%)_Space_8.2_MB_(63.58%)
3+
4+
#include<vector>
5+
#include<string>
6+
7+
classSolution {
8+
public:
9+
std::vector<std::vector<std::optional<bool>>> cache;
10+
11+
boolisMatch(const std::string& s,const std::string& p) {
12+
cache.resize(s.length() +1, std::vector<std::optional<bool>>(p.length() +1));
13+
returnisMatchHelper(s, p,0,0);
14+
}
15+
16+
private:
17+
boolisMatchHelper(const std::string& s,const std::string& p,int i,int j) {
18+
if (j == p.length()) {
19+
return i == s.length();
20+
}
21+
22+
if (cache[i][j].has_value()) {
23+
return cache[i][j].value();
24+
}
25+
26+
bool firstMatch = (i < s.length() && (s[i] == p[j] || p[j] =='.'));
27+
28+
bool result;
29+
if ((j +1) < p.length() && p[j +1] =='*') {
30+
result = (firstMatch &&isMatchHelper(s, p, i +1, j)) ||isMatchHelper(s, p, i, j +2);
31+
}else {
32+
result = firstMatch &&isMatchHelper(s, p, i +1, j +1);
33+
}
34+
35+
cache[i][j] = result;
36+
return result;
37+
}
38+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp