leetCode-Merge Sorted Array

Posted kevincong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetCode-Merge Sorted Array相关的知识,希望对你有一定的参考价值。

Description:
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.

Solution:

//初始化三个指针,i指向A含有元素的尾部,j指向B的尾部,k指向A存放元素的尾部
//对A和B逆序遍历,从两个数组中找出最大元素存放一次放到k指向的位置
//最后看看B有没有放完(不用管A,因为如果i>=0说明剩余元素就该放在原位置上,如果i<0,说明j没有放完,还得继续遍历B)
class Solution {
   public void merge(int A[], int m, int B[], int n) {
    int i=m-1, j=n-1, k=m+n-1;
    while (i>-1 && j>-1) A[k--]= (A[i]>B[j]) ? A[i--] : B[j--];
    while (j>-1)         A[k--]=B[j--];
}
}

 

 


以上是关于leetCode-Merge Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

2.1.1Remove Duplicates from Sorted Arr

Sorted Union

LeetCode 1213. Intersection of Three Sorted Arrays

Java—Remove Deplicates from Sorted Array(顺序数组中去重位置)

python 二维数组排序

Count the number of occurrences in a sorted array