项目作者: eMahtab

项目描述 :
Merge two sorted arrays
高级语言:
项目地址: git://github.com/eMahtab/merge-sorted-array.git
创建时间: 2020-04-25T06:45:37Z
项目社区:https://github.com/eMahtab/merge-sorted-array

开源协议:

下载


Merge Sorted Array

https://leetcode.com/problems/merge-sorted-array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  1. The number of elements initialized in nums1 and nums2 are m and n respectively.
  2. 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]

Implementation :

  1. class Solution {
  2. public void merge(int[] nums1, int m, int[] nums2, int n) {
  3. int c1 = 0, c2 = 0;
  4. int index = 0;
  5. int[] clone = nums1.clone();
  6. while(c1 < m && c2 < n) {
  7. if(nums2[c2] <= clone[c1]) {
  8. nums1[index++] = nums2[c2++];
  9. } else {
  10. nums1[index++] = clone[c1++];
  11. }
  12. }
  13. while(c2 < n) {
  14. nums1[index++] = nums2[c2++];
  15. }
  16. while(c1 < m) {
  17. nums1[index++] = clone[c1++];
  18. }
  19. }
  20. }