Merge Sorted Array

来源:互联网 发布:股票数据采集 编辑:程序博客网 时间:2024/05/17 03:11

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.

  主要是比较两个数组中每个数字的大小,如果数组A的第一元素小于B的第一个元素,则A数组的第二个元素与B的第一个元素进行比较,

依次类推。

   

class Solution {public:    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {        if(m<=0&&n<=0) return;        int a=0,b=0;        int result[m+n];        for(int i=0;i<m+n;i++){            if(a<m && b<n)            {            if(nums1[a]<nums2[b])            {                result[i]=nums1[a];                a++;            }            else{                result[i]=nums2[b];                b++;                }            }            else if(a<m&&b>=n){                result[i]=nums1[a];                a++;            }            else if(a>=m&&b<n)            {                result[i]=nums2[b];                b++;            }             else return;        }        for(int i=0;i<m+n;i++)        {            nums1[i]=result[i];        }            }};


class Solution {public:    void merge(int A[], int m, int B[], int n) {        int temp[m+n];        int i = 0, j = 0, t = 0;        while(i < m && j < n)        {            if(A[i] < B[j])                temp[t++] = A[i++];            else                temp[t++] = B[j++];        }        while(i < m)            temp[t++] = A[i++];        while(j < n)            temp[t++] = B[j++];        while(--t >= 0)            A[t] = temp[t];    }};


采用尾插法,

算法思想是:由于合并后A数组的大小必定是m+n,所以从最后面开始往前赋值,先比较A和B中最后一个元素的大小,把较大的那个插入到m+n-1的位置上,再依次向前推。如果A中所有的元素都比B小,那么前m个还是A原来的内容,没有改变。如果A中的数组比B大的,当A循环完了,B中还有元素没加入A,直接用个循环把B中所有的元素覆盖到A剩下的位置。

假设B中元素长,分两种可能,A先放完,B没放完,则最后把剩下的B中数组放入。2、B中数字比A中的大,先放完,则因为剩下的A中数据时排序的,不用进行插入;

假设A中元素长,与上面类似。

class Solution {public:    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {                int count=m+n-1;        m--;        n--;        while(m>=0&&n>=0){            nums1[count--]=nums1[m]>nums2[n]?nums1[m--]:nums2[n--];        }        while(n>=0) nums1[count--]=nums2[n--];    }};


#include<iostream>#include<algorithm>using namespace std;void merge(int* a, int m, int* b, int n);int main(){int a[] = { 2, 3, 5, 7, 9 };int b[] = { 1, 4, 6, 8, 12, 15, 16, 17 };int m = sizeof(a) / sizeof(a[0]);int n = sizeof(b) / sizeof(b[0]);merge(a, m, b, n);for (int i = 0; i < m + n; i++)cout << a[i] << ' ';system("pause");return 0;}void merge(int* a, int m, int* b, int n){int index = m + n-1;int aindex = m - 1;int bindex = n - 1;while (aindex >= 0 && bindex >= 0){if (a[aindex] > b[bindex]){a[index] = a[aindex];aindex--;index--;}else{a[index] = b[bindex];bindex--;index--;}}while (bindex >= 0){a[index--] = b[bindex--];}}


0 0