zoukankan      html  css  js  c++  java
  • [Leetcode]-Merge Sorted Array

    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.

    Hide Tags: Array。 Two Pointers

    题目:合并两个已排好序的数组。要求合并后相同保持排好序
    思路:採用两个指针分别从两个数组开头向后移。而且比較。提前须要分配一个能存下两个数组的暂时数组。

    void merge(int* nums1, int m, int* nums2, int n) {
    
        int lpos = 0, rpos = 0, tmpos = 0;
        int* tem = (int*)malloc(sizeof(int)*(m+n));
    
        while(lpos < m && rpos < n)
        {
            if(nums1[lpos] < nums2[rpos])
                tem[tmpos++] = nums1[lpos++];
            else
                tem[tmpos++] = nums2[rpos++];
        }
        while(lpos < m)
        {
             tem[tmpos++] = nums1[lpos++];
        } 
        while(rpos < n)
        {
             tem[tmpos++] = nums2[rpos++];
        }
    
        int i = 0;
        for(i=0;i<m+n;i++)
        {
            nums1[i] = tem[i];
        }
        free(tem);
    }
  • 相关阅读:
    Java 9 模块解耦的设计策略
    Spring Data JPA 事务锁
    如何配置Spring Boot Tomcat
    Spring Cloud Turbine
    Spring Boot 测试时的日志级别
    Spring Boot中使用RSocket
    构造函数
    递归函数的使用
    有序数列的二分搜索
    Java第一次代码作业汇总
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/7016420.html
Copyright © 2011-2022 走看看