LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
           *添加6
[1,2,3,0,0,0]
     |
[2,5,6]

         *添加5
[1,2,3,0,0,6]
     |
  [2,5,6]

       *添加3
[1,2,3,0,5,6]
     |
    [2,5,6]

     *添加2
[1,2,3,3,5,6]
   |
  [2,5,6]

   *nums2 访问结束,此时的 nums1 即为结果
[1,2,2,3,5,6]
   |
    [2,5,6]
class Solution {
 public:
  void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    while (m && n) {
      if (nums1[m - 1] > nums2[n - 1]) {
        nums1[m + n - 1] = nums1[m - 1];
        --m;
      } else {
        nums1[m + n - 1] = nums2[n - 1];
        --n;
      }
    }
    while (n--) {  // nums2 仍有剩余元素
      nums1[n] = nums2[n];
    }
  }
};