|
1 | 1 | package easy;
|
2 | 2 |
|
3 |
| -import utils.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 | public class RemoveElement {
|
| 20 | + //then I looked at the Editorial solution, really neat!!! Super elegant and smart! |
| 21 | + public int removeElement_editorial_solution_1(int[] nums, int val){ |
| 22 | + //use two pointers, increment j as long as its not equal to val, return i in the end |
| 23 | + int i = 0; |
| 24 | + for(int j = 0; j < nums.length; j++){ |
| 25 | + if(nums[j] != val) nums[i++] = nums[j]; |
| 26 | + } |
| 27 | + return i; |
| 28 | + } |
| 29 | + |
| 30 | + public int removeElement_editorial_solution_2(int[] nums, int val){ |
| 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 | + int i = 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 | + return i; |
| 43 | + } |
| 44 | + |
| 45 | + //just throw all numbers that are equal to val to the end and make a count of it |
22 | 46 | public int removeElement(int[] nums, int val) {
|
23 |
| - for(int i = 0; i < nums.length; i++){ |
24 |
| - int start = 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 |
| - return 0; |
| 47 | + int count = 0; |
| 48 | + int len = nums.length, throwPosition = len-1; |
| 49 | + for(int i = 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 | + int temp = nums[throwPosition]; |
| 58 | + nums[throwPosition] = nums[i]; |
| 59 | + nums[i] = temp; |
| 60 | + throwPosition--; |
| 61 | + } |
| 62 | + } |
| 63 | + return len-count; |
33 | 64 | }
|
34 | 65 |
|
35 | 66 | public static void main(String...strings){
|
36 | 67 | RemoveElement test = new RemoveElement();
|
37 |
| - int[] nums = new int[]{3,2,2,3}; |
38 |
| - int val = 3; |
39 |
| - test.removeElement(nums, val); |
| 68 | +// int[] nums = new int[]{3,2,2,3}; |
| 69 | +// int val = 3; |
| 70 | + |
| 71 | + int[] nums = new int[]{2,2,3}; |
| 72 | + int val = 2; |
| 73 | + |
| 74 | +// int[] nums = new int[]{1}; |
| 75 | +// int val = 1; |
| 76 | + System.out.println(test.removeElement(nums, val)); |
40 | 77 | }
|
41 | 78 | }
|
0 commit comments