LeetCode之Merge Sorted Array
【摘要】 1、问题
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note: You may assume that nums1 has enou...
1、问题
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.
2、代码实现
-
package leetcode.chenyu.test;
-
-
public class MergeSortedArray {
-
public static void main(String[] args) {
-
int a[] = new int[10];
-
a[0] = -1;
-
a[1] = 0;
-
a[2] = 4;
-
a[3] = 7;
-
int b[] = {2, 5};
-
int len = a.length;
-
for (int x : a)
-
System.out.print(x);
-
merge(a, 10, b, 2);
-
for (int x : a)
-
System.out.print(x);
-
}
-
public static void merge(int[] nums1, int m, int[] nums2, int n) {
-
if (nums1 == null || m == 0 || n == 0)
-
return;
-
int i = 0, j = 0, k = 0;
-
int index = 0;
-
int nums3[] = new int[m];
-
for (int x = m - 1; x>= 0; x--) {
-
if (x - 1 > 0)
-
if (nums1[x] == 0 && nums1[x - 1] != 0) {
-
index = x;
-
break;
-
}
-
}
-
int value = nums1[index];
-
System.out.println("index is:" + index);
-
while (j < n && i < index) {
-
if (nums1[i] <= nums2[j]) {
-
System.out.print("if i is " + i + "k is " + k + "nums1[" + i + "]" + nums1[i] + "\n");
-
nums3[k] = nums1[i];
-
i++;
-
} else {
-
System.out.print("if j is " + j + "k is " + k + "nums2["+ j + "]" + nums2[j] + "\n");
-
nums3[k] = nums2[j];
-
j++;
-
}
-
k++;
-
}
-
System.out.println("i + 1 < m" + (i + 1 < m));
-
System.out.println("i is :" + i);
-
System.out.println("nums1[i]" + nums1[i]);
-
System.out.println("nums1[index]" + nums1[index]);
-
System.out.println("nums1[i + 1] != nums1[index]" + (nums1[i + 1] != nums1[index]));
-
if (i + 1 < m && nums1[i] != nums1[index]) {
-
System.out.println("if if");
-
for (int f = i; f < index; f++) {
-
nums3[k] = nums1[f];
-
}
-
}
-
for (int x : nums3) {
-
System.out.print(x);
-
-
}
-
for (int h = 0; h < nums3.length; h++) {
-
nums1[h] = nums3[h];
-
}
-
// nums1 = nums3;
-
-
}
-
}
-
3、结果
-
-1047000000index is:4
-
if i is 0k is 0nums1[0]-1
-
if i is 1k is 1nums1[1]0
-
if j is 0k is 2nums2[0]2
-
if i is 2k is 3nums1[2]4
-
if j is 1k is 4nums2[1]5
-
i + 1 < mtrue
-
i is :3
-
nums1[i]7
-
nums1[index]0
-
nums1[i + 1] != nums1[index]false
-
if if
-
-1024570000-1024570000
提到上去会有下标越界异常,好吧,后面再来分析为什么出错,今天先记录到这里
文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。
原文链接:chenyu.blog.csdn.net/article/details/77626163
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)