Java 1ms method


  • 0
    S

    public class MoveZeroes {

    public static void moveZeroes(int[] nums) {
    	int i = 0, j = 0, length = nums.length;
    	while (true) {
    		// find i that nums[i] = 0
    		while (i < length && nums[i] != 0)
    			++i;
    		// no zero in the array
    		if (i == length)
    			break;
    		// find j that nums[j] != 0
    		// all numbers in the array are 0
    		while (j < length && nums[j] == 0)
    			++j;
    		if (j == length)
    			break;
    		// find!
    		// 0 is after non-0, continue searching with j=i+1
    		if (j < i) {
    			j = i + 1;
    		} else {
    			nums[i++] = nums[j];
    			nums[j++] = 0;
    		}
    	}
    }
    

    }


  • -1
    G
    public ListNode partition(ListNode head, int x) {
    
       
    	ListNode head1=new ListNode(-1),head2=new ListNode(-1),temp1=null,temp2=null, temp = null;
    	temp1 = head1;
    	temp2 = head2;
    
    	while(head!=null){
    		if(head.val >= x){
    			temp = head.next;
    			head.next=null;
    			temp2.next = head;
    			temp2 = temp2.next;
    			head = temp;			
    		}
    		else{
    			temp1.next = head;
    			temp1 = head;
    			head = head.next;
    		}
    		
    	}
    	
    	temp1.next=head2.next;
    			
    	return head1.next;       
     
     
    }
    

    }


  • 0
    S

    dude, what r u doing?


  • 0
    G

    Logic = Keep all the values that are equal to or greater than 'x' in a separate list and then after the whole traversal add this list to the end of the list that has smaller than 'x' values.

    Basically, there are 2 Lists : one with smaller values and one with greater values.


  • 0
    O

    The problem specifically requires that "You must do this in-place without making a copy of the array."
    Your "separate list" defeats that requirement.


Log in to reply
 

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