|
| 1 | +packageeasy; |
| 2 | + |
| 3 | +importutils.CommonUtils; |
| 4 | + |
| 5 | +/**283. Move Zeroes QuestionEditorial Solution My Submissions |
| 6 | +Total Accepted: 105705 |
| 7 | +Total Submissions: 231420 |
| 8 | +Difficulty: Easy |
| 9 | +Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. |
| 10 | +
|
| 11 | +For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. |
| 12 | +
|
| 13 | +Note: |
| 14 | +You must do this in-place without making a copy of the array. |
| 15 | +Minimize the total number of operations.*/ |
| 16 | +publicclassMoveZeroes { |
| 17 | +publicvoidmoveZeroes_Editorial_solution2(int[]nums){ |
| 18 | +//this solutoin is the most optimal since it minimizes the number of operations |
| 19 | +//the idea is to swap the non-zero element to the first zero number position |
| 20 | +for(inti =0,j =0;i <nums.length &&j <nums.length;i++){ |
| 21 | +if(nums[i] !=0){ |
| 22 | +inttemp =nums[i]; |
| 23 | +nums[i] =nums[j]; |
| 24 | +nums[j] =temp; |
| 25 | +j++; |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | +publicvoidmoveZeroes_Editorial_solution1(int[]nums){ |
| 31 | +//keep the last non-zero index and keep overwriting it, then append zeroes to fill the end |
| 32 | +intj =0,i =0; |
| 33 | +for(;j <nums.length;j++){ |
| 34 | +if(nums[j] !=0){ |
| 35 | +nums[i++] =nums[j]; |
| 36 | + } |
| 37 | + } |
| 38 | +for(;i <nums.length;i++){ |
| 39 | +nums[i] =0; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | +//then I came up with this solution and got it AC'ed! Cheers! |
| 44 | +//basically, find the next non-zero number and swap it with the current zero number |
| 45 | +//Apparently it's not the most optimal, since this is basically an O(n^2) solution, then I turned to Editorial solutions |
| 46 | +publicvoidmoveZeroes(int[]nums){ |
| 47 | +for(inti =0;i <nums.length-1;i++){ |
| 48 | +if(nums[i] ==0){ |
| 49 | +intj =i+1; |
| 50 | +while(j <nums.length &&nums[j] ==0){ |
| 51 | +j++; |
| 52 | + } |
| 53 | +if(j >=nums.length)return; |
| 54 | +else { |
| 55 | +inttemp =nums[j]; |
| 56 | +nums[j] =nums[i]; |
| 57 | +nums[i] =temp; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | +//this approach won't preserve the relative order of the non-zero numbers |
| 64 | +publicvoidmoveZeroes_1st_attempt(int[]nums) { |
| 65 | +inti =0,j =nums.length-1; |
| 66 | +while(i <j){ |
| 67 | +if(nums[i] ==0){ |
| 68 | +inttemp =nums[j]; |
| 69 | +nums[j] =nums[i]; |
| 70 | +nums[i] =temp; |
| 71 | +j--; |
| 72 | + }else { |
| 73 | +i++; |
| 74 | + } |
| 75 | + } |
| 76 | +CommonUtils.printArray(nums); |
| 77 | + } |
| 78 | + |
| 79 | +publicstaticvoidmain(String...strings){ |
| 80 | +MoveZeroestest =newMoveZeroes(); |
| 81 | +int[]nums =newint[]{0,1,0,3,12}; |
| 82 | +test.moveZeroes_Editorial_solution2(nums); |
| 83 | + } |
| 84 | +} |