88. 合并两个有序数组
88. 合并两个有序数组
https://leetcode-cn.com/problems/merge-sorted-array/description/
package com.test; import java.util.Arrays; /** * @Author stono * @Date 2018/8/27 上午7:49 */ public class Lesson088 { public static void main(String[] args) { // int[] nums1 = {1, 2, 3, 0, 0, 0}; // int m = 3; int [] nums1 = {2,0}; int m = 1; // int[] nums2 = {2, 5, 6}; // int n = 3; int[] nums2 = {1}; int n = 1; merge(nums1, m, nums2, n); System.out.println(Arrays.toString(nums1)); } public static void merge(int[] nums1, int m, int[] nums2, int n) { if (n == 0) { return; } // 创建一个新的数组,保留比较结果 int[] res = new int[nums1.length]; int i = 0, j = 0, k = 0; for (; i < m; ) { for (; j < n; ) { int i1 = nums1[i]; int j1 = nums2[j]; if (i1 < j1) { res[k] = i1; i++; k++; break; } else { res[k] = j1; j++; k++; } } if (n - j == 0) { break; } } while (i < m) { res[k] = nums1[i]; k++; i++; } while (j < n) { res[k] = nums2[j]; k++; j++; } for (int i1 = 0; i1 < res.length; i1++) { nums1[i1] = res[i1]; } System.out.println(Arrays.toString(nums1)); } }