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

  • 相关阅读:
    闲谈系列之一——数据库主键GUID
    一个简单通用权限管理系统,求各位帮忙看看
    php 计算指定年份的周总数与及第几周的开始日期和结束日期(从周一开始)
    创建虚拟机流程详细过程链接
    阿里云CDN加速设置
    sublime Text3 快捷键
    Linux命令(centos7)
    分布式数据库
    mysql 分区和分表
    Linux crontab 命令格式与详细例子
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5432267.html
Copyright © 2011-2022 走看看