Merge Sorted Array
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.
1 /************************************************************************* 2 > File Name: LeetCode088.c 3 > Author: Juntaran 4 > Mail: [email protected] 5 > Created Time: Tue 17 May 2016 15:28:11 PM CST 6 ************************************************************************/ 7 8 /************************************************************************* 9 10 Merge Sorted Array 11 12 Given two sorted integer arrays nums1 and nums2, 13 merge nums2 into nums1 as one sorted array. 14 15 Note: 16 You may assume that nums1 has enough space 17 (size that is greater or equal to m + n) 18 to hold additional elements from nums2. 19 The number of elements initialized in nums1 and nums2 20 are m and n respectively. 21 22 ************************************************************************/ 23 24 #include <stdio.h> 25 26 void merge(int* nums1, int m, int* nums2, int n) 27 { 28 int i = m - 1; 29 int j = n - 1; 30 31 while( i>=0 && j>=0 ) 32 { 33 if( nums1[i] > nums2[j] ) 34 { 35 nums1[i+j+1] = nums1[i]; 36 i --; 37 } 38 else 39 { 40 nums1[i+j+1] = nums2[j]; 41 j --; 42 } 43 } 44 while( j >= 0 ) 45 { 46 nums1[i+j+1] = nums2[j]; 47 j --; 48 } 49 }
时间: 2024-11-10 03:54:14