Problem
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 nums1and 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. The number of elements initialized in nums1and nums2 are m and n respectively.
Analysis
- 题目是把两个sorted的数组合并成一个,这里假设数组1足够大,所以直接合并到数组1
- 记录当前要写入的index,初始值为 m+n-1
- 对两个数组从后往前扫描
- 谁比较大,谁就先写入
- 同时update index
- Time: O(m+n)
- Space: O(1)
Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public void merge(int[] nums1, int m, int[] nums2, int n) { | |
int idx = m+n-1; | |
int i = m-1; | |
int j = n-1; | |
//fill in reverse order | |
//larger one first | |
while(i>=0 && j>=0){ | |
if(nums1[i]<nums2[j]){ | |
nums1[idx--] = nums2[j--]; | |
}else{ | |
nums1[idx--] = nums1[i--]; | |
} | |
} | |
//fill the rest of nums2 | |
while(j>=0){ | |
nums1[idx--] = nums2[j--]; | |
} | |
} | |
} |
Reference
[1] https://leetcode.com/problems/merge-sorted-array/
No comments:
Post a Comment