Merge Sorted Array

来源:互联网 发布:java时间格式化天 编辑:程序博客网 时间:2024/05/29 19:12

题目描述

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.

题目解答

解题思路

合并两个有序的数组,并且放在其中一个数组中,我们可以从尾部开始选取最大值,然后填充在最后面,即比较两个数组中的最大值,每次选取最大的放在数组的尾部。

代码实现

public class Solution {    public void merge(int[] nums1, int m, int[] nums2, int n) {        if(m == 0 && n == 0)            return ;        int leftS1 = 0, rightS1 = m-1;        int leftS2 = 0, rightS2 = n-1;        int i = n+m-1;        while(leftS1 <= rightS1 && leftS2 <= rightS2){            if(nums1[rightS1] > nums2[rightS2]){                nums1[i] = nums1[rightS1];                rightS1--;            }else {                nums1[i] = nums2[rightS2];                rightS2--;            }            i--;        }        while(leftS2 <= rightS2) {            nums1[i] = nums2[rightS2];            rightS2--;            i--;        }    }}
0 0
原创粉丝点击