[0]
0
[1]
1
This is the case my code failed on...... Should not the size of first array be 1?? Help please.....
Hi @LHearen
Thanks for your reply. I finally knew the right code, but just curious about this test case. Below is my original code that trigger this case failure. Thanks.
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
if(nums1.empty()) {nums1=nums2; return;}
if(nums2.empty()) return;
if(m+n < nums1.size() + nums2.size()) return;
for(int i=m+n-1,
j=m-1,
k=n-1; j>=0 && k>=0 && j<i; ){
nums1[i--] = nums1[j] > nums2[k] ? nums1[j--] : nums2[k--];
if(j==-1 && k>=0){
while(k>=0)
nums1[i--] = nums2[k--];
break;
}
}
}
};
@Bambu A reference
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
int r1 = m-1, r2 = n-1, r = m+n-1;
while(r1>=0 && r2>=0)
nums1[r--] = nums1[r1]>nums2[r2]? nums1[r1--] : nums2[r2--];
while(r2 >= 0)
nums1[r--] = nums2[r2--];
}
};
@Bambu Something wrong with your logic here. Check my code first and if you're still stuck in there, let me know.