Java solution with O(n) time and O(1) space


  • 0
    E
    public class Solution {
        public void sortColors(int[] nums) {
            int[] sorted = new int[nums.length];
            for(int i = 0; i< sorted.length; i ++){
                sorted[i] = 1;
            }
            int head = 0, tail = nums.length -1;
            for(int current: nums){
                if(current ==0) sorted[head++] = 0;
                else if(current == 2) sorted[tail--] = 2;
            }
            //nums = sorted;
            for(int i = 0; i< sorted.length; i ++){
            	nums[i]= sorted[i];
            }
        }
    }
    

    Question is: when I used this statement:
    nums = sorted; //which is in comment right now
    Leecode did not view nums as newly sorted array and reject it. When I use the for loop to assign each value to nums from sorted array, it passes....


Log in to reply
 

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