首页 > 其他 > 详细

LeetCode Merge Sorted Array

时间:2015-11-20 12:28:49      阅读:249      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/merge-sorted-array/

从后往前,比较A 和 B 两个数组,谁的大谁就放在最后面。

Time Complexity: O(n). Space: O(1).

AC Java:

 1 public class Solution {
 2     public void merge(int A[], int m, int B[], int n) {
 3         //put compared result to the last of A, to maintain the unsorted elements in A
 4         int pa = m-1;
 5         int pb = n-1;
 6         int pc = m+n-1;
 7 
 8         for(;pc>=0;pc--){
 9             //Remember to check if index pa is out of bound FIRST!!!
10             //This part is super tricky, second is check if pb is out of bound
11             //The order of three comparison could not be exchanged
12             //If pa is out of bound, A[pa]>B[pb] will give error since A[-1] is not accepted
13             //If pb is out of bound, A[pa]>B[pb] will give error since B[-1] is not accepted
14             //So check pa and pb FIRST
15             if(pa>=0 && ( pb<0 || A[pa]>B[pb])){
16                 A[pc] = A[pa--];
17             }else{
18                 A[pc] = B[pb--];
19             }
20         }
21     }
22 }

 

LeetCode Merge Sorted Array

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4980297.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!