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--;
                }
            }
        }
    };

  • 相关阅读:
    [super dealloc]内存释放的先后顺序
    NSString的常用方法
    Xcode开发技巧之code snippets(代码片段)
    关于oc运行时 isa指针详解
    ios快捷键
    自动释放池的使用
    【字典树】统计难题
    数据结构实验之图论五:从起始点到目标点的最短步数(BFS)
    字典树模板
    数据结构实验之串三:KMP应用
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5432267.html
Copyright © 2011-2022 走看看