Leetcode 88th question-merge Sorted Array

Source: Internet
Author: User

The title means: Merge two ordered arrays into the first array, so that the merged arrays are still ordered, and assume that the first array has enough space.

Problem-solving ideas: At the beginning of this topic, I am also desperate to start from the beginning, the result is very troublesome, always have one or two positions go wrong, the array is not as simple as a linked list to insert a node, we have to solve is the location of the insertion node problem. Fortunately, the internet looked at other people's practice, suddenly thought can be traversed from the back, because each array is ordered, compare the last position of the two array element size can determine the final position of the element, and finally use this idea ac this problem.

#include <stdio.h> #include <stdlib.h>void merge (int a[], int m, int b[], int n) {    int i=0,j=0;while (m& &n) {if (a[m-1]>b[n-1]) {a[m+n-1]=a[m-1];m--;} else{a[m+n-1]=b[n-1];n--;}} while (n) {a[n-1]=b[n-1];n--;}} int main () {int m,n,i;while (scanf ("%d%d", &m,&n)!=eof) {int *a= (int *) malloc (sizeof (int) * (m+n)); int *b= (int *) malloc (sizeof (int) *n), for (i=0;i<m;i++) scanf ("%d", &a[i]), for (i=0;i<n;i++) scanf ("%d", &b[i]); for (i= m;i<m+n;i++) A[i]=0;merge (A,m,b,n), for (i=0;i<m+n;i++) printf ("%d", A[i]);p rintf ("\ n");} return 0;}


Leetcode 88th question-merge Sorted Array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.