Another Java solution (is there a better way for swap in Java?)


  • 0
    S
    public class Solution {
        public void sortColors(int[] nums) {
            // treat start as stack for 0s and end as stack for 2s
            int start = 0;
            int end = nums.length-1;
            for (int i=0; i<=end;) {
                while (nums[i] == 2 && i < end) {
                    int temp = nums[i];
                    nums[i] = nums[end];
                    nums[end] = temp;
                    end--;
                    continue;
                }
                while (nums[i] == 0 && i > start) {
                    int temp = nums[i];
                    nums[i] = nums[start];
                    nums[start] = temp;
                    start++;
                    continue;
                }
                i++;
            }
        }
    }

  • 4
    G

    well there is..
    for this problem, you already know nums[i]=2,
    so we can do this:

    nums[i]=nums[end];
    nums[end]=2;

  • 0
    L

    well so many waste swap....and the O(n^2) time?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.