problem:
Sol:
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
m--;
n--;
while (1) {
if (n < 0)
return;
else if (m < 0) {
while (n >= 0) {
A[n] = B[n];
n--;
}
return;
}
else if (A[m] == B[n]) {
A[m + n + 1] = A[m];
A[m + n] = A[m];
m--;
n--;
} else if (A[m] > B[n]) {
A[m + n + 1] = A[m];
m--;
} else {
A[m + n + 1] = B[n];
n--;
}
}
}
};
====== Smaller one ======
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectivel
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectivel
Sol:
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
m--;
n--;
while (1) {
if (n < 0)
return;
else if (m < 0) {
while (n >= 0) {
A[n] = B[n];
n--;
}
return;
}
else if (A[m] == B[n]) {
A[m + n + 1] = A[m];
A[m + n] = A[m];
m--;
n--;
} else if (A[m] > B[n]) {
A[m + n + 1] = A[m];
m--;
} else {
A[m + n + 1] = B[n];
n--;
}
}
}
};
====== Smaller one ======
void
merge(
int
A[],
int
m,
int
B[],
int
n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int
count=m+n-1;
m--; n--;
while
(m>=0 && n>=0){
A[count--] = A[m]>B[n]? A[m--]:B[n--];
}
while
(n>=0){ A[count--] = B[n--];}
}
OR
void
merge(
int
A[],
int
m,
int
B[],
int
n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int
k=m+n-1;
int
i=m-1;
int
j=n-1;
while
(i>=0 && j>=0){
if
(A[i]>B[j]){
A[k--]=A[i--];
}
else
{
A[k--]=B[j--];
}
}
while
(j>=0){
A[k--]=B[j--];
}
return
;
}
=== This attempt ====
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
if (n == 0) {
return;
} else if (m == 0) {
nums1 = nums2;
return;
}
while (m > 0 && n > 0) {
if (nums1[m - 1] == nums2[n - 1]) {
nums1[m + n - 1] = nums1[m - 1];
nums1[m + n - 2] = nums1[m - 1];
m--;
n--;
} else if (nums1[m - 1] > nums2[n - 1]) {
nums1[m + n - 1] = nums1[m - 1];
m--;
} else {
nums1[m + n - 1] = nums2[n - 1];
n--;
}
}
if (m == 0) {
while (n > 0) {
nums1[n - 1] = nums2[n - 1];
n--;
}
}
return;
}
======== Better one ====
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
while (n > 0) {
int first = (m > 0 ? nums1[m - 1] : INT_MIN);
int second = (n > 0 ? nums2[n - 1]: INT_MIN);
if (m == 0 || second >= first) {
nums1[m + n - 1] = second;
n--;
} else {
nums1[m + n - 1] = first;
m--;
}
}
}
};
No comments:
Post a Comment