合并两个有序数组,放在A中,A中的空间足够。
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 m andn respectively.
从后往前放,比较A和B的从后往前的,比较大的放在m+n-1的位置。然后一直减减。
class Solution { public: void merge(int A[], int m, int B[], int n) {while(m > 0 && n > 0) { if (A[m-1] > B[n-1]) { A[m+n-1] = A[m-1]; m--; } else { A[m+n-1] = B[n-1]; n--; } } if (m == 0) while(n > 0) { A[n-1] = B[n-1]; n--; } return ; } };
也可以写短一点:
class Solution { public: void merge(int A[], int m, int B[], int n) { int nowA = m - 1, nowB = n - 1, last = n + m - 1; while(nowA >= 0 && nowB >=0) { A[last--] = A[nowA] > B[nowB] ? A[nowA--] : B[nowB--]; } while(nowB >= 0) A[last--] = B[nowB--]; return ; } };
2015/03/31:
class Solution { public: void merge(int A[], int m, int B[], int n) { int i = m - 1, j = n - 1, k = m + n - 1; while(i >=0 && j >=0){ A[k--] = A[i] > B[j] ? A[i--] : B[j--]; } while(i >= 0){ A[k--] = A[i--]; // 多余了 } while(j >= 0){ A[k--] = B[j--]; } } };
原来多余的写了一部分 A的不用赋值给A可以,因为就是A啊
python:
class Solution: # @param A a list of integers # @param m an integer, length of A # @param B a list of integers # @param n an integer, length of B # @return nothing(void) def merge(self, A, m, B, n): i, j, k= m -1, n -1, m + n -1 while i >=0 and j >=0: if A[i] > B[j]: A[k] = A[i] i -= 1 else: A[k] = B[j] j -= 1 k -= 1 while j >= 0: A[k] = B[j] k -= 1 j -= 1