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

    Description:

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

    Code:

     void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
            vector<int> nums(nums1);
            
            int itrNums1 = 0, itrNums2 = 0;;
           
            vector<int>::iterator itr = nums.begin();
            while(itrNums1!=m && itrNums2!=n)
            {
        //如果把下面的if判断改为三目运算符会出现"runtime error"
                if (nums1[itrNums1] <= nums2[itrNums2])
                {
                    *itr++ = nums1[itrNums1++];
                }
                else
                {
                    *itr++ = nums2[itrNums2++];
                }
            }
            while(itrNums1!=m)
            {
                *itr++ = nums1[itrNums1++];
            }
            while(itrNums2!=n)
            {
                *itr++ = nums2[itrNums2++];
            }
            for (int i = 0 ; i < m+n; ++i)
                nums1[i] = nums[i];
        }
  • 相关阅读:
    ZOJ 3795 Grouping
    ZOJ 3791 An Easy Game
    ZOJ 3790 Consecutive Blocks
    POJ 1451 T9
    POJ 1141 Brackets Sequence
    POJ 2411 Mondriaan's Dream
    POJ 2513 Colored Sticks
    Eclipse 快捷键大全
    C# lock关键字(多线程)
    C# 内部类
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4586271.html
Copyright © 2011-2022 走看看