zoukankan      html  css  js  c++  java
  • 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++;
             }
        }
  • 相关阅读:
    vim代码对齐
    在liunx中,快速查找到以前使用过的命令行
    linux文件权限与目录设置
    ASP常用代码
    存储过程
    WebService
    SNS
    浪曦博客系统
    SQL事件探查器与索引优化向导
    光盘AJAX
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5107821.html
Copyright © 2011-2022 走看看