概述
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
- Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
解法
从前往后排不方便,题目中隐含的意思就是nums1数组一定容得下两个数组合并后的长度,所以令k指向合并后数组的最后一位,从末尾开始依次将较大的数存入数组。要注意外部循环和内部赋值的判断条件,防止超出数组范围
public void merge(int[] nums1, int m, int[] nums2, int n) {
int k=m+n-1;
int i=m-1,j=n-1;
while(j>=0)
nums1[k--]=(i>=0&&nums1[i]>nums2[j])?nums1[i--]:nums2[j--];
}
Runtime: 2 ms, faster than 100.00% of Java online submissions for Merge Sorted Array.
Memory Usage: 37.4 MB, less than 46.42% of Java online submissions for Merge Sorted Array.
最后
以上就是危机绿茶为你收集整理的LeetCode——Merge Sorted Array解法的全部内容,希望文章能够帮你解决LeetCode——Merge Sorted Array解法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复