首页 > 代码库 > LeetCode "Merge Sorted Array"
LeetCode "Merge Sorted Array"
My first reaction: move all A elements back by n positions, and start everything from A[0] and B[0]. But a smarter idea is to start everything from the end :) So no need to move. Just to take care of all cases.
class Solution { public: void merge(int A[], int m, int B[], int n) { int cnt = m + n - 1; int bi = n - 1, ai = m - 1; while (cnt >= 0) { int tmp = 0; if (ai < 0 && bi >= 0) { tmp = B[bi--]; } else if (bi < 0 && ai >= 0) { tmp = A[ai--]; } else if (bi >=0 && ai >= 0) { if (A[ai] >= B[bi]) tmp = A[ai--]; else tmp = B[bi--]; } A[cnt--] = tmp; } } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。