数组去重
方法有很多种,举几个例子吧,个人感觉没有标准答案,只要思路开阔,方法可以有很多种
1. 先借助sort排序,排序后将每个元素和它的下一个元素做对比,相同则把前一个或后一个借助splice将其删掉
2. 借助冒泡的思想,将每个元素和它后面的元素依次做对比,相同了则把后面的那个相同的删了
3. 借助一个新数组,每次在老数组中取出一个元素,和新数组的元素借助includes方法比较是已存在,不存在就把元素存进新数组
4. 借助filtet遍历数组,利用indexOf判断该元素第一次出现时的下标和当前下标是否相同,相同则返回,不同就表示前面出现过(filter会将符合条件的元素组成一个新的数组)
import java.util.*; public class Main { public static void main(String[] args) { int[] arr = {1, 3, 3, 3, 4, 4, 3, 3, 2}; int left = 0, right = arr.length - 1; int mid = -1; int lastLeft = -1; int lastRight = -1; int lastLeftRepeat = -1; int lastRightRepeat = -1; while (left < right) { int curLeft = arr[left]; int curRight = arr[right]; if (arr[left] > arr[left + 1]) { mid = left; } if (arr[right] > arr[right - 1]) { mid = right; } if (left > 0 && arr[left] == lastLeft) { if (lastLeftRepeat != arr[left]) { lastLeftRepeat = arr[left]; } arr[left] = -1; } if (right < arr.length - 1 && arr[right] == lastRight) { if (lastRightRepeat != arr[right]) { lastRightRepeat = arr[right]; } arr[right] = -1; } if (arr[left] == arr[right]) { if (lastLeftRepeat != arr[left] && lastRightRepeat == arr[right]) { lastLeftRepeat = arr[left]; arr[left] = -1; } else if (lastLeftRepeat == arr[left] && lastRightRepeat != arr[right]) { lastRightRepeat = arr[right]; arr[right] = -1; } else if (lastLeftRepeat != arr[left] && lastRightRepeat != arr[right]) { lastLeftRepeat = arr[left]; lastRightRepeat = arr[right]; arr[right] = -1; } if (right != mid) { right --; lastRight = curRight; } if (left != mid) { left ++; lastLeft = curLeft; } } else if (arr[left] > arr[right]) { if (right != mid) { right --; lastRight = curRight; } } else { if (left != mid) { left ++; lastLeft = curLeft; } } } ArrayList<Integer> res = new ArrayList<>(arr.length); for (int i : arr) { if (i != -1) res.add(i); } System.out.println(Arrays.toString(res.toArray())); } }