leetcode----Merge Sorted Array

package leedcode;

import java.lang.reflect.Array;
import java.util.ArrayList;

import javax.crypto.spec.IvParameterSpec;

/** * @author duola Given two sorted integer arrays nums1 and nums2, merge nums2 * into nums1 as one sorted array. 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. */

public class MergeTwoArray {

    public static void merge(int[] nums1, int m, int[] nums2, int n) {
        // 思路是把nums2中的元素合并到nums1中,放到nums1后面
        int k = m + n - 1;
        m = m - 1;
        n = n - 1;// 从0开始,所以最后一个下标识n-1

        while (m >= 0 && n >= 0) {
            nums1[k--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--];// 每次只取一个较大的元素,放到最后
        }

        // 如果n>m将执行这一段
        while (n >= 0) {
            nums1[k--] = nums2[n--];
        }
    }

    public static void main(String[] args) {

        int[] a = new int[100];
        int[] b = new int[100];
        for (int i = 0; i < 10; i++) {
            a[i] = i;
            b[i] = 2 + i;
        }
        merge(a, 10, b, 10);
        for (int i = 0; i < 10 + 10; i++) {
            System.out.print(a[i] + "\t");
        }
    }
}

你可能感兴趣的:(LeetCode)