首页 > 代码库 > LeetCode "Sort Colors"
LeetCode "Sort Colors"
For the one pass solution... first I tried to build white\blue from red, but not working anyway. Then I referred someone‘ code, to build red\blue from white. Working now. The pointers‘ behavior deserves more thinking:
class Solution {public: void swap(int A[], int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } void sortColors(int A[], int n) { if (n == 0 || n == 1) return; if (n == 2) { if (A[0] > A[1]) swap(A, 0, 1); return; } int i0 = 0; int i1 = 0; int i2 = n - 1; while (i1<=i2) { if (A[i1] == 0) { swap(A, i0++, i1++);
// Reason i1 also inc here: all 2s have been swapped back,
// so all left are 0\1s - in any case, we don‘t need consider twice. so move on continue; } else if (A[i1] == 2) { swap(A, i1, i2--); continue; } i1 ++; } }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。