Why my java solution is giving wrong answer!?


  • 0
    J

    for input [1, 0], my solution give output [1, 0]. but i think it should give [0,1]. please help to tell me why

    public class Solution {
        public void sortColors(int[] nums) {
            if(nums==null || nums.length<=1)    return;
            int len=nums.length;
            int left=0;
            int right=len-1;
            for(int i=0;i<=right;i++){
                if(nums[i]==2){
                    swap(nums[i--], nums[right--]);
                }else if(nums[i]==0){
                    swap(nums[i], nums[left++]);
                }
            }
        }
        
        public void swap(int a, int b){
            int tmp=a;
            a=b;
            b=tmp;
        }
    }

  • 0
    S

    your swap function won't make a difference.

    public static void sortColors(int[] nums) {
    	int left = 0;
    	int right = nums.length - 1;
    	int tmp = 0;
    	for (int i = 0; i <= right; i ++) {
    		if (nums[i] == 0) {
    			tmp = nums[left];
    			nums[left++] = nums[i];
    			nums[i] = tmp;
    		} else if (nums[i] == 2) {
    			tmp = nums[right];
    			nums[right--] = nums[i];
    			nums[i] = tmp;
    			i--;
    		}
    	}
    }

Log in to reply
 

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