Skip to content

Commit e14abdf

Browse files
author
wangpeng
committed
refactor: 更新_27_removeElement解法二
1 parent b2dbdc1 commit e14abdf

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/pp/arithmetic/leetcode/_27_removeElement.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,10 @@ public static void main(String[] args) {
5555
System.out.println(element.removeElement(new int[]{3, 2, 2, 3}, 3));
5656
System.out.println(element.removeElement(new int[]{0, 1, 2, 2, 3, 0, 4, 2}, 2));
5757
System.out.println(element.removeElement(new int[]{3, 1, 0}, 11));
58+
//解法二
59+
System.out.println(element.removeElement2(new int[]{3, 2, 2, 3}, 3));
60+
System.out.println(element.removeElement2(new int[]{0, 1, 2, 2, 3, 0, 4, 2}, 2));
61+
System.out.println(element.removeElement2(new int[]{3, 1, 0}, 11));
5862
}
5963

6064
/**
@@ -63,6 +67,8 @@ public static void main(String[] args) {
6367
* 1、先对数组进行排序
6468
* 2、找到==val的起始位置和终止位置
6569
* 3、将终止位置后的数字前移至起始位置
70+
* <p>
71+
* 更新一个更简洁的写法 {@link _27_removeElement#removeElement2(int[], int)}
6672
*
6773
* @param nums
6874
* @param val
@@ -97,4 +103,26 @@ public int removeElement(int[] nums, int val) {
97103
return len - ei + si - 2;
98104
}
99105
}
106+
107+
/**
108+
* 解法二,写法更简洁
109+
*
110+
* @param nums
111+
* @param val
112+
* @return
113+
*/
114+
public int removeElement2(int[] nums, int val) {
115+
116+
int retLen = 0;
117+
int insertIndex = 0;
118+
for (int i = 0; i < nums.length; i++) {
119+
if (nums[i] == val) {
120+
continue;
121+
}
122+
nums[insertIndex++] = nums[i];
123+
retLen++;
124+
}
125+
126+
return retLen;
127+
}
100128
}

0 commit comments

Comments
 (0)