LeetCode: Sort Colors

没写出来,看到网上一个非常好的code,不过这个code不太容易想出来

 1 class Solution {

 2 public:

 3     void sortColors(int A[], int n) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         int pos[3] = {};

 7         for (int i = 0; i < n; i++) {

 8             int cur = A[i];

 9             for (int j = 2; j >= cur; j--) {

10                 A[pos[j]] = j;

11                 pos[j]++;

12             }

13         }

14     }

15 };

下面是一个比较容易想出来的code。

 1 class Solution {

 2 public:

 3     void sortColors(int A[], int n) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         int left = 0;

 7         int right = n-1;

 8         int mid = n-1;

 9         while (left <= mid) {

10             if (A[left] == 2) {

11                 int tmp = A[right];

12                 A[right] = A[left];

13                 A[left] = tmp;

14                 right--;

15                 if (right < mid) mid = right;

16             }

17             if (A[left] == 1) {

18                 int tmp = A[mid];

19                 A[mid] = A[left];

20                 A[left] = tmp;

21                 mid--;

22             }

23             if (A[left] == 0) left++;

24         }

25     }

26 };

 C#

 1 public class Solution {

 2     public void SortColors(int[] nums) {

 3         int left = 0, right = nums.Length - 1, mid = nums.Length - 1;

 4         while (left <= mid) {

 5             if (nums[left] == 2) {

 6                 int tmp = nums[right];

 7                 nums[right] = nums[left];

 8                 nums[left] = tmp;

 9                 right--;

10                 if (right < mid) mid = right;

11             }

12             if (nums[left] == 1) {

13                 int tmp = nums[mid];

14                 nums[mid] = nums[left];

15                 nums[left] = tmp;

16                 mid--;

17             }

18             if (nums[left] == 0) left++;

19         }

20     }

21 }
View Code

 

你可能感兴趣的:(LeetCode)