zoukankan      html  css  js  c++  java
  • Leetcode题目: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.

    题目解答:可以确定,两个有序数组在合并之后的大小为m + n,并且依旧有序。为了防止从前面访问元素时,导致元素移动次数过于频繁,可以直接从数组的最后面开始比较。思路很简单,就不赘述了,直接看代码吧。

    代码如下:

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

  • 相关阅读:
    java 8 stream sql left join =》 jooq & Flink & Scala
    Maven error: lambda expressions are not supported in -source 1.7
    error C2039: 'SetWindowTextA' : is not a member of 'CString'
    循环队列(循环数组)中元素个数的计算
    数据结构之堆
    理解C语言声明的优先级规则
    内联汇编中的asm和__asm__
    程序启动时的堆栈
    局部变量与堆栈
    BCD码干什么用的?
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5432267.html
Copyright © 2011-2022 走看看