• LeetCode(88): Merge Sorted Array


    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.

    题意:合并两个有序数组,将nums2的元素合并到nums1中,并且假设nums1数组空间是足够的。其中注意函数的参数,m和n,它们是指要合并的每个数组元素的个数,其分别小于等于各自数组长度。

    思路:按照归并排序的思路,因为归并排序中给定的是一个数组的两个区间,所以通常情况下会借助O(n)大小的辅助空间。

    代码:

    public void merge(int[] nums1, int m, int[] nums2, int n) {
             int pos1=0,pos2=0;
             int all_count = 0;
             int[] temp = new int[m];
             System.arraycopy(nums1,0,temp,0,m);
         
             while(pos1<m&&pos2<n){
                 if(temp[pos1]<nums2[pos2]){
                     nums1[all_count] = temp[pos1];
                     pos1++;
                     all_count++;
                 }else{
                     nums1[all_count] = nums2[pos2];
                     pos2++;
                     all_count++;
                 }
             }
             while(pos1<m){
                 nums1[all_count] = temp[pos1];
                 pos1++;
                all_count++;
             }
             while(pos2<n){
                 nums1[all_count] = nums2[pos2];
                 pos2++;
                 all_count++;
             }
        }
  • 相关阅读:
    随笔
    json对象的默认排序问题
    SQl死锁随想
    疑惑
    .netportal
    WCF中出现方法出现无法匹配的异常
    自动播放图片,可以调整速度。
    一个二级树形菜单,初始显示为全部展开,适用于分类较少的情况。
    整理了一下以后需要用的软件
    缩略图,大图,同页显示
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5107821.html
Copyright © 2020-2023  润新知