zoukankan      html  css  js  c++  java
  • 【LeetCode】88. 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 nums1and nums2 are m and n respectively.

    提示:

    此题在题干中已经提示了nums1的大小是nums1与nums2的有效数字大小之和,因此我们可以从后往前(从大到小)排序,这样就仅涉及到赋值操作而不需要swap。

    代码:

    class Solution {
    public:
        void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
            int idx = m + n - 1;
            int i = m - 1, j = n - 1;
            while (i > -1 && j > -1 && idx > -1) {
                if (nums1[i] > nums2[j]) nums1[idx--] = nums1[i--];
                else nums1[idx--] = nums2[j--];
            }
            if (i < 0) {
                while (idx > -1) nums1[idx--] = nums2[j--];
            }
        }
    };

     在论坛中发现了一种非常简洁的写法:

    class Solution {
    public:
        void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
            int i = m - 1, j = n - 1, tar = m + n - 1;
            while (j >= 0) {
                nums1[tar--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
            }
        }
    };

    两者的思路是一样的。

  • 相关阅读:
    对vue中nextTick()的理解及使用场景说明
    微信小程序的视图与渲染
    1分钟了解微信小程
    Idea搭建Spring+SpringMvc+Mybatis框架集成项目
    idea 新建不了servlet文件 方法(1)
    idea使用大全(加载mysql驱动)
    开发文档规范
    如何架构一个框架
    mac os x
    mongodb rockmongo
  • 原文地址:https://www.cnblogs.com/jdneo/p/4773269.html
Copyright © 2011-2022 走看看