Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are mand n respectively.
題目大概的意思就是給出兩個已經排序好的數組,合並這兩個數組並要求仍然有序。
1 class Solution {
2 public:
3 void merge(int A[], int m, int B[], int n) {
4 int i,j,k;
5 for(k=m+n-1,i=m-1,j=n-1;k>=0;k--){
6 if((A[i]>B[j]||j<0)&&(i>=0)){
7 A[k]=A[i--];
8 }else{
9 A[k]=B[j--];
10 }
11 }
12 }
13 };
代碼比較簡單,簡單的說一下思路,
新數組的長度是m+n,從新數組的最後一個元素開始循環插入數組
if((A[i]>B[j]||j<0)&&(i>=0)) 這句代碼可以這樣理解,對應著兩種情況:
情況一 如果數組A當前下標的元素大於數組B當前下標的元素並且數組A沒有循環結束
情況二 如果數組B的元素已經循環完而數組A的元素還沒有循環完
這兩種情況下就將元素保存到新的數組A中。
