zoukankan      html  css  js  c++  java
  • 88. Merge Sorted Array

    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_88 {
    public:
    	// merge nums2 into nums1 as one sorted array.
    	void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    
    		if (m==0)
    		{
    			for (int i = 0; i < n;i++)
    			{
    				nums1.push_back(nums2[i]);
    			}
    			return;
    		}
    		if (n==0)
    		{
    			return;
    		}
    		int len1 = m - 1;
    		int len2 = n - 1;
    		int index = m + n - 1;
    		while (len1>=0&&len2>=0)
    		{
    			if (nums2[len2]>nums1[len1])
    			{
    				nums1[index--] = nums2[len2--];
    			}
    			else
    			{
    				nums1[index--] = nums1[len1--];
    			}
    		}
    
    		while (len2>=0)
    		{
    			nums1[index--] = nums2[len2--];
    		}
    
    		return;
    	}
    
    	void merge(int A[], int m, int B[], int n) {
    		int i = m - 1;
    		int j = n - 1;
    		int index = m + n - 1;
    
    		while (i>=0&&j>=0)
    		{
    			A[index--] = (A[i] > B[j]) ? A[i--] : B[j--];
    		}
    		while (j>=0)
    		{
    			A[index--] = B[j--];
    		}
    		return;
    	}
    };
    
    

    题目来源

  • 相关阅读:
    the Agiles Scrum Meeting 8
    the Agiles Scrum Meeting 7
    the Agiles Scrum Meeting 6
    项目使用说明——英文版
    第十次例会
    第九次例会
    第八次例会
    第六次例会
    第七次例会
    第五次例会
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8793434.html
Copyright © 2011-2022 走看看