前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode程序员面试金典】面试题 10.01. Sorted Merge LCCI

【LeetCode程序员面试金典】面试题 10.01. Sorted Merge LCCI

作者头像
韩旭051
发布2020-06-23 10:45:50
2890
发布2020-06-23 10:45:50
举报
文章被收录于专栏:刷题笔记

You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.

Initially the number of elements in A and B are m and n respectively.

Example:

Input: A = [1,2,3,0,0,0], m = 3 B = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sorted-merge-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

双指针

A的后面是空的,所以可以换一个思路,从最后一个值开始判断最大值存入

从后往前遍历,就不会被内存空间所限制

代码语言:javascript
复制
class Solution {
    public void merge(int[] A, int m, int[] B, int n) {
        int a=m-1;
        int b=n-1;
        for(int i=m+n-1;i>=0;i--){
            if(b<0||(a>=0&&A[a]>B[b])){
                A[i]=A[a];
                a--;
            }else{
                A[i]=B[b];
                b--;
            }
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/05/13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 双指针
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档