|
11 | 11 | Example:
|
12 | 12 | Given input array nums = [3,2,2,3], val = 3
|
13 | 13 |
|
14 |
| -Your function should return length = 2, with the first two elements of nums being 2.*/ |
15 |
| -public class _27 { |
16 |
| - //then I looked at the Editorial solution, really neat!!! Super elegant and smart! |
17 |
| - public int removeElement_editorial_solution_1(int[] nums, int val) { |
18 |
| - //use two pointers, increment j as long as its not equal to val, return i in the end |
19 |
| - int i = 0; |
20 |
| - for (int j = 0; j < nums.length; j++) { |
21 |
| - if (nums[j] != val) { |
22 |
| - nums[i++] = nums[j]; |
23 |
| - } |
24 |
| - } |
25 |
| - return i; |
26 |
| - } |
27 |
| - |
28 |
| - public int removeElement_editorial_solution_2(int[] nums, int val) { |
29 |
| - //this approach is very similar to the one below that I came up totally by myself, but it's much concise |
30 |
| - //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! |
31 |
| - int i = 0; |
32 |
| - int n = nums.length; |
33 |
| - while (i < n) { |
34 |
| - if (nums[i] == val) { |
35 |
| - nums[i] = nums[n - 1]; |
36 |
| - n--; |
37 |
| - } else { |
38 |
| - i++; |
39 |
| - } |
40 |
| - } |
41 |
| - return i; |
42 |
| - } |
43 |
| - |
44 |
| - //just throw all numbers that are equal to val to the end and make a count of it |
45 |
| - public int removeElement(int[] nums, int val) { |
46 |
| - int count = 0; |
47 |
| - int len = nums.length; |
48 |
| - int 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) { |
55 |
| - break; |
56 |
| - } |
57 |
| - if (nums[i] == val) { |
58 |
| - count++; |
59 |
| - int temp = nums[throwPosition]; |
60 |
| - nums[throwPosition] = nums[i]; |
61 |
| - nums[i] = temp; |
62 |
| - throwPosition--; |
63 |
| - } |
64 |
| - } |
65 |
| - return len - count; |
66 |
| - } |
| 14 | +Your function should return length = 2, with the first two elements of nums being 2. |
| 15 | + */ |
67 | 16 |
|
68 |
| - public static void main(String... strings) { |
69 |
| - _27 test = new _27(); |
70 |
| -// int[] nums = new int[]{3,2,2,3}; |
71 |
| -// int val = 3; |
72 |
| - |
73 |
| - int[] nums = new int[]{2, 2, 3}; |
74 |
| - int val = 2; |
| 17 | +public class _27 { |
75 | 18 |
|
76 |
| -// int[] nums = new int[]{1}; |
77 |
| -// int val = 1; |
78 |
| - System.out.println(test.removeElement(nums, val)); |
79 |
| - } |
80 |
| -} |
| 19 | + public static class Solution1 { |
| 20 | + public int removeElement(int[] nums, int val) { |
| 21 | + int i = 0; |
| 22 | + for (int j = 0; j < nums.length; j++) { |
| 23 | + if (nums[j] != val) { |
| 24 | + nums[i++] = nums[j]; |
| 25 | + } |
| 26 | + } |
| 27 | + return i; |
| 28 | + } |
| 29 | + } |
| 30 | +} |
0 commit comments