Golang语法不支持while循环,自增不能当表达式使用,所以用它写这道题看起来很丑
func merge(a []int, m int, b []int, n int) []int{
tmp := make([]int, m+n)
i, j, k := 0, 0, 0
for i < m && j < n {
if a[i] < b[j] {
tmp[k] = a[i]
k++
i++
} else {
tmp[k] = b[j]
k++
j++
}
}
for i < m {
tmp[k] = a[i]
k++
i++
}
for j < n {
tmp[k] = b[j]
k++
j++
}
for k := 0; k< m+n;k++ {
a[k] = tmp[k]
}
return a
}
这道题用Java写,看起来就比较优雅
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] tmp = new int[m + n];
int i,j,k;
i = j = k = 0;
while(i < m && j < n){
if(nums1[i] <= nums2[j]){
tmp[k++] = nums1[i++];
}else{
tmp[k++] = nums2[j++];
}
}
while(i < m) tmp[k++] = nums1[i++];
while(j < n) tmp[k++] = nums2[j++];
for(k = 0;k < (m+n); k++){
nums1[k] = tmp[k];
}
}
}
有疑问加站长微信联系(非本文作者)