|
1 | 1 | packageeasy;
|
2 | 2 |
|
3 |
| -importutils.CommonUtils; |
4 |
| - |
5 | 3 | /**27. Remove Element
|
6 | 4 |
|
7 | 5 | Total Accepted: 135216
|
|
19 | 17 |
|
20 | 18 | Your function should return length = 2, with the first two elements of nums being 2.*/
|
21 | 19 | publicclassRemoveElement {
|
| 20 | +//then I looked at the Editorial solution, really neat!!! Super elegant and smart! |
| 21 | +publicintremoveElement_editorial_solution_1(int[]nums,intval){ |
| 22 | +//use two pointers, increment j as long as its not equal to val, return i in the end |
| 23 | +inti =0; |
| 24 | +for(intj =0;j <nums.length;j++){ |
| 25 | +if(nums[j] !=val)nums[i++] =nums[j]; |
| 26 | + } |
| 27 | +returni; |
| 28 | + } |
| 29 | + |
| 30 | +publicintremoveElement_editorial_solution_2(int[]nums,intval){ |
| 31 | +//this approach is very similar to the one below that I came up totally by myself, but it's much concise |
| 32 | +//Here, it didn't check whether nums[n-1] will be equal to val, because in the next iteration, it will still check that number, smart! |
| 33 | +inti =0,n =nums.length; |
| 34 | +while(i <n){ |
| 35 | +if(nums[i] ==val){ |
| 36 | +nums[i] =nums[n-1]; |
| 37 | +n--; |
| 38 | + }else { |
| 39 | +i++; |
| 40 | + } |
| 41 | + } |
| 42 | +returni; |
| 43 | + } |
| 44 | + |
| 45 | +//just throw all numbers that are equal to val to the end and make a count of it |
22 | 46 | publicintremoveElement(int[]nums,intval) {
|
23 |
| -for(inti =0;i <nums.length;i++){ |
24 |
| -intstart =i; |
25 |
| -while(i <nums.length &&nums[i] ==val){ |
26 |
| -i++; |
27 |
| -} |
28 |
| -if(i ==nums.length)i--; |
29 |
| -nums[start] =nums[i]; |
30 |
| -} |
31 |
| -CommonUtils.printArray(nums); |
32 |
| -return0; |
| 47 | +intcount =0; |
| 48 | +intlen =nums.length,throwPosition =len-1; |
| 49 | +for(inti =0;i <=throwPosition;i++){ |
| 50 | +while(throwPosition >=0 &&nums[throwPosition] ==val) { |
| 51 | +throwPosition--; |
| 52 | +count++; |
| 53 | + } |
| 54 | +if(throwPosition == -1 ||i >=throwPosition)break; |
| 55 | +if(nums[i] ==val){ |
| 56 | +count++; |
| 57 | +inttemp =nums[throwPosition]; |
| 58 | +nums[throwPosition] =nums[i]; |
| 59 | +nums[i] =temp; |
| 60 | +throwPosition--; |
| 61 | + } |
| 62 | + } |
| 63 | +returnlen-count; |
33 | 64 | }
|
34 | 65 |
|
35 | 66 | publicstaticvoidmain(String...strings){
|
36 | 67 | RemoveElementtest =newRemoveElement();
|
37 |
| -int[]nums =newint[]{3,2,2,3}; |
38 |
| -intval =3; |
39 |
| -test.removeElement(nums,val); |
| 68 | +//int[] nums = new int[]{3,2,2,3}; |
| 69 | +//int val = 3; |
| 70 | + |
| 71 | +int[]nums =newint[]{2,2,3}; |
| 72 | +intval =2; |
| 73 | + |
| 74 | +//int[] nums = new int[]{1}; |
| 75 | +// int val = 1; |
| 76 | +System.out.println(test.removeElement(nums,val)); |
40 | 77 | }
|
41 | 78 | }
|