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 nums1 and nums2 are m and n respectively.

    我们数据结构书上在讲归并排序时,是将数组插入到新的数组中,这个是插到原来的数组中,我们只需要将第二个数组的元素一个一个插进来就好

    class Solution {
    public:
       void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    		nums1.resize(m + n);
    		int nums1_postion = 0, nums2_postion = 0, count_nums2 = 0;
    		for (;nums1_postion<m + n&&nums2_postion < n;++nums1_postion)
    		{
    			if (nums1_postion >= m + count_nums2 || (nums1[nums1_postion] > nums2[nums2_postion]))
    			{
    				++count_nums2;
    				int temp = m+count_nums2-1;
    				for (;temp > nums1_postion;--temp)
    				{
    					nums1[temp] = nums1[temp - 1];
    				}
    				nums1[nums1_postion] = nums2[nums2_postion++];
    			}
    		}
    	}
    };
    

      

  • 相关阅读:
    js中的日期控件My97 DatePicker
    list中慎用remove
    ehcache注解全面解析
    servlet
    SpringMVC注解@RequestMapping全面解析
    SpringMVC注解@RequestParam全面解析
    lucene全文检索
    jenkins和hudson
    Mysql与PostgreSql数据库学习笔记
    前端学习笔记
  • 原文地址:https://www.cnblogs.com/csudanli/p/5877259.html
Copyright © 2011-2022 走看看