• 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++;
             }
        }
  • 相关阅读:
    Node buffer模块缓冲区
    Node url模块
    Node querystring
    Node fs模块同步读取写入追加
    Linux Shell 量的自增
    Compare, sort, and delete duplicate lines in Notepad ++
    PL SQL 基础
    Oracle alter table modify column Syntax example
    Oracle to_char格式化函数
    oracle to_char FM099999
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5107821.html
Copyright © 2020-2023  润新知