zoukankan      html  css  js  c++  java
  • LeetCode_88. Merge Sorted Array

    88. Merge Sorted Array

    Easy

    Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

    Note:

    • The number of elements initialized in nums1 and nums2 are m and n respectively.
    • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

    Example:

    Input:
    nums1 = [1,2,3,0,0,0], m = 3
    nums2 = [2,5,6],       n = 3
    
    Output: [1,2,2,3,5,6]
    package leetcode.easy;
    
    public class MergeSortedArray {
    	@org.junit.Test
    	public void test() {
    		int[] nums1 = { 1, 2, 3, 0, 0, 0 };
    		int m = 3;
    		int[] nums2 = { 2, 5, 6 };
    		int n = 3;
    		print(nums1);
    		print(nums2);
    		merge(nums1, m, nums2, n);
    		print(nums1);
    	}
    
    	public void merge(int[] nums1, int m, int[] nums2, int n) {
    		for (int i = m, j = 0; i < nums1.length && j < nums2.length; i++, j++) {
    			nums1[i] = nums2[j];
    		}
    		sort(nums1, m + n);
    	}
    
    	private static void sort(int[] nums, int m) {
    		for (int i = 0; i < m - 1; i++) {
    			for (int j = 0; j < m - 1 - i; j++) {
    				if (nums[j] > nums[j + 1]) {
    					int temp = nums[j];
    					nums[j] = nums[j + 1];
    					nums[j + 1] = temp;
    				}
    			}
    		}
    	}
    
    	private static void print(int[] nums) {
    		for (int i = 0; i < nums.length; i++) {
    			System.out.print(nums[i] + " ");
    		}
    		System.out.println();
    	}
    }
    
  • 相关阅读:
    Eclipse之注释操作
    Eclipse之查找、替换操作
    思维游戏(4)之有问题的楼房
    第七层 应用层
    第三章 进程
    第一章 导论
    软件开发流程
    单元测试
    Google Chrome浏览器调试
    python安装完毕后,提示找不到ssl模块的解决步骤
  • 原文地址:https://www.cnblogs.com/denggelin/p/11596151.html
Copyright © 2011-2022 走看看