Leetcode 75 Sort Colors

来源:互联网 发布:openwrt 软件 编辑:程序博客网 时间:2024/05/29 17:22

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

排序的问题,我直接用了最简单的冒泡。

实际上还是有其他的方法的。

public class Solution {    public void sortColors(int[] nums) {        for(int i = 0; i<nums.length; i++){            for(int j = i + 1; j< nums.length; j++){                if(nums[i]>nums[j]){                    int temp = nums[i];                    nums[i] = nums[j];                    nums[j] = temp;                }            }        }    }}


比如使用bucket的方法


private static final int MAX = 3;public void sortColors(int[] nums) {    int[] buckets = new int[MAX];    for(int num : nums) buckets[num]++;    for(int p = 0, val = 0; val < MAX; val++) {        for(int count = 0; count < buckets[val]; count++) {            nums[p++] = val;        }    }}

// one pass in place solutionvoid sortColors(int A[], int n) {    int j = 0, k = n - 1;    for (int i = 0; i <= k; ++i){//只有当i当前指向的元素为1的时候才会移动        if (A[i] == 0 && i != j)//当ij不等的时候 i至少会比j多加一次 因此 i会在j的后面            swap(A[i--], A[j++]);//i保持不动 队首指针后移        else if (A[i] == 2 && i != k)//找到2 就放在最后面            swap(A[i--], A[k--]);//队尾指针前移  i保持不动    }}// one pass in place solutionvoid sortColors(int A[], int n) {    int j = 0, k = n-1;    for (int i=0; i <= k; i++) {        if (A[i] == 0)            swap(A[i], A[j++]);        else if (A[i] == 2)            swap(A[i--], A[k--]);    }}

题外话,好久不刷题,被炼狱级别的workload吓疯了。

我总是处于各种焦虑的状态,担心着很久很久以后的事情。

似乎我们从一生下来就被赶着走,没人问你开不开心,只关心你够不够达到人们觉得的“优秀”。

我不知道自己是不是真的开心。

我走得一帆风顺,似乎是,又似乎不是自己想要的东西。

希望能坚持吧。

0 0
原创粉丝点击