Skip to content

Improved cpp readmes #1

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
103 changes: 41 additions & 62 deletions src/main/cpp/g0001_0100/s0004_median_of_two_sorted_arrays/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,70 +52,49 @@ The overall run time complexity should be `O(log (m+n))`.
* `1 <= m + n <= 2000`
* -106 <= nums1[i], nums2[i] <= 106

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));
## Solution

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

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));
class Solution {
public:
double findMedianSortedArrays(std::vector& nums1, std::vector& 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;
}
}
```

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))).
};
```
Original file line number Diff line number Diff line change
Expand Up @@ -36,65 +36,51 @@ Given a string `s`, return _the longest palindromic substring_ in `s`.
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.

To solve the Longest Palindromic Substring problem in Java using a `Solution` class, we'll follow these steps:

1. Define a `Solution` class with a method named `longestPalindrome`.
2. Initialize variables to keep track of the start and end indices of the longest palindromic substring found so far (`start` and `end`).
3. Iterate through the string `s`:
- For each character in the string, expand around it to check if it forms a palindrome.
- Handle both odd-length and even-length palindromes separately.
- Update `start` and `end` indices if a longer palindrome is found.
4. Return the substring from `start` to `end`.
5. Handle edge cases where the input string is empty or has a length of 1.

Here's the implementation:

```java
public class Solution {

public String longestPalindrome(String s) {
if (s == null || s.length() < 1) return "";
int start = 0;
int end = 0;

for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}

return s.substring(start, end + 1);
}

private int expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}

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

// Test cases
String s1 = "babad";
System.out.println("Example 1 Output: " + solution.longestPalindrome(s1));
## Solution

String s2 = "cbbd";
System.out.println("Example 2 Output: " + solution.longestPalindrome(s2));
```cpp
#include
#include
#include

String s3 = "a";
System.out.println("Example 3 Output: " + solution.longestPalindrome(s3));
class Solution {
public:
std::string longestPalindrome(const std::string& s) {
// Transform s into newStr with delimiters
std::string newStr(s.length() * 2 + 1, '#');
for (int i = 0; i < s.length(); ++i) {
newStr[2 * i + 1] = s[i];
}

String s4 = "ac";
System.out.println("Example 4 Output: " + solution.longestPalindrome(s4));
}
}
```
std::vector dp(newStr.length(), 0);
int friendCenter = 0, friendRadius = 0;
int lpsCenter = 0, lpsRadius = 0;

for (int i = 0; i < newStr.length(); ++i) {
dp[i] = (friendCenter + friendRadius > i)
? std::min(dp[2 * friendCenter - i], friendCenter + friendRadius - i)
: 1;

while (i + dp[i] < newStr.length() && i - dp[i] >= 0 && newStr[i + dp[i]] == newStr[i - dp[i]]) {
dp[i]++;
}

if (friendCenter + friendRadius < i + dp[i]) {
friendCenter = i;
friendRadius = dp[i];
}

if (lpsRadius < dp[i]) {
lpsCenter = i;
lpsRadius = dp[i];
}
}

This implementation provides a solution to the Longest Palindromic Substring problem in Java.
int start = (lpsCenter - lpsRadius + 1) / 2;
int length = lpsRadius - 1;
return s.substr(start, length);
}
};
```
96 changes: 35 additions & 61 deletions src/main/cpp/g0001_0100/s0006_zigzag_conversion/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,70 +41,44 @@ string convert(string s, int numRows);
* `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
* `1 <= numRows <= 1000`

To solve the Zigzag Conversion problem in Java using a `Solution` class, we'll follow these steps:

1. Define a `Solution` class with a method named `convert`.
2. Create an array of strings to represent each row of the zigzag pattern.
3. Initialize variables to keep track of the current row (`row`) and the direction of traversal (`down`).
4. Iterate through each character in the input string `s`.
- Append the current character to the string representing the current row.
- If we reach the first or last row, change the direction of traversal accordingly.
- Update the current row based on the direction of traversal.
5. Concatenate the strings representing each row to form the final zigzag conversion.
6. Return the concatenated string.
7. Handle edge cases where the number of rows is 1 or the input string is empty.

Here's the implementation:

```java
public class Solution {

public String convert(String s, int numRows) {
if (numRows == 1 || s.length() <= numRows) {
return s;
}

StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
rows[i] = new StringBuilder();
}

int row = 0;
boolean down = false;
## Solution

for (char c : s.toCharArray()) {
rows[row].append(c);
if (row == 0 || row == numRows - 1) {
down = !down;
}
row += down ? 1 : -1;
}
```cpp
#include
#include

StringBuilder result = new StringBuilder();
for (StringBuilder sb : rows) {
result.append(sb);
class Solution {
public:
std::string convert(std::string s, int numRows) {
int sLen = s.length();
if (numRows == 1) {
return s;
}

return result.toString();
}

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

// Test cases
String s1 = "PAYPALISHIRING";
int numRows1 = 3;
System.out.println("Example 1 Output: " + solution.convert(s1, numRows1));

String s2 = "PAYPALISHIRING";
int numRows2 = 4;
System.out.println("Example 2 Output: " + solution.convert(s2, numRows2));

String s3 = "A";
int numRows3 = 1;
System.out.println("Example 3 Output: " + solution.convert(s3, numRows3));
int maxDist = numRows * 2 - 2;
std::string buf;
buf.reserve(sLen);
for (int i = 0; i < numRows; i++) {
int index = i;
if (i == 0 || i == numRows - 1) {
while (index < sLen) {
buf += s[index];
index += maxDist;
}
} else {
while (index < sLen) {
buf += s[index];
index += maxDist - i * 2;
if (index >= sLen) {
break;
}
buf += s[index];
index += i * 2;
}
}
}
return buf;
}
}
```

This implementation provides a solution to the Zigzag Conversion problem in Java.
};
```
Loading