Skip to content

# int32bit / leetcode

Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
README.md
in.txt
solve.cpp

## Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

## Solution

```void merge_from_start(vector<int> &num1, int m, vector<int> &num2, int n) {
int i = 0,j = 0, k = 0;
vector<int> result(m + n, 0);
while (i < m && j < n) {
if (num1[i] <= num2[j]) {
result[k++] = num1[i++];
} else {
result[k++] = num2[j++];
}
}
while (i < m) {
result[k++] = num1[i++];
}
while (j < n) {
result[k++] = num2[j++];
}
num1.clear();
for_each(begin(result), end(result), [&num1](int i){num1.push_back(i);});
}```

• `num1[i] >= num2[j]`, 则`num1[total--] = num1[i--]`
• `num2[j] > num1[i]`, 则`num1[total--] = num2[j--]`
• 重复以上步骤直到num1或者num2结束
```void merge_from_end(vector<int> &num1, int m, vector<int> &num2, int n) {
int k = m + n - 1;
int i = m - 1, j = n - 1;
while (i >= 0 && j >= 0) {
if (num1[i] >= num2[j])
num1[k--] = num1[i--];
else
num1[k--] = num2[j--];
}
while (j >= 0)
num1[k--] = num2[j--];
}```

## 扩展

You can’t perform that action at this time.