leetcode 88. Merge Sorted Array

来源:互联网 发布:linux查看系统字体设置 编辑:程序博客网 时间:2024/06/03 00:51

题目内容
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.

题目分析
给定两个排序好的数组nums1和nums2,将两个数组按照归并到数组nums1中,依然保证数组nums1是有序的。
通过分析发现,如果从头开始,即index=0的情况来处理两个数组,可能需要申请额外的m+n的空间,不够简便。可以从 index=m+n-1,m-1,n-1,数组最后一位开始处理,不断的向前。即可。

public class Solution {       public void merge(int[] nums1, int m, int[] nums2, int n) {       int ind = n + m - 1 ;       int p1 = m-1 , p2 = n-1;       while(ind >= 0){          if(p1 < 0) nums1[ind--] = nums2[p2--];          else if(p2 < 0) nums1[ind--] = nums1[p1--];          else nums1[ind--] = (nums1[p1] > nums2[p2]) ? nums1[p1--] : nums2[p2--] ;       }   }}
0 0
原创粉丝点击