[原解]一個迴圈遍歷所有元素,用兩個索引使兩個值可互相比較(索引 i 有條件移動,索引 j 規律+1移動);
若兩個值不相等,即將不相等次數+1,索引 i 方能+1移動,直到遍歷結束。
[後解]一個迴圈切成兩半,各自遍歷,最後再將取得的不重複陣列元素個數加總回傳。
// [原解]
// getUnDuplicatedCount
class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
} else if (nums.length < 2) {
return 1;
} else {
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[i] != nums[j]) {
// get different element to move index
nums[++i] = nums[j];
}
}
return i + 1;
}
}
}
// [後解]
public class Test {
public static void main(String[] args) {
int[] array = {0, 1, 0, 3, 12};
int start = 0, end = array.length - 1;
int middle = (start + end) / 2;
int leftCount = getNonDuplicatedCount(array, start, middle);
int rightCount = getNonDuplicatedCount(array, middle + 1, end);
System.out.println(leftCount + rightCount);
}
public static int getNonDuplicatedCount(int[] array, int start, int end){
int count = 0;
Arrays.sort(array);
while (end >= start) {
if (array[start] != array[++start]) {
count += 2;
}
start++;
}
return count;
}
}
如有敘述錯誤,還請不吝嗇留言指教,thanks!