三种解法:
第一种是在数组中查找O(n^2)
第二种是在HashSet中查找O(n)
第三种是在有序数组中查找O(nlogn)
JAVA
class Solution { public int countElements(int[] arr) { int res = 0; for(int i = 0; i < arr.length; i++){ int cur = arr[i]+1; for(int j = 0; j < arr.length; j++){ if(cur == arr[j]){ res++; break; //!!!bug } } } return res; } }
class Solution { public int countElements(int[] arr) { Set<Integer> set = new HashSet<>(); for(int x : arr){ set.add(x); } int res = 0; for(int x: arr){ if(set.contains(x+1)) res++; } return res; } }
class Solution { public int countElements(int[] arr) { Arrays.sort(arr); int res = 0; int length = 1; for(int i = 1; i < arr.length; i++){ if(arr[i-1] != arr[i]){ if(arr[i-1] + 1 == arr[i]){ res += length; } length = 0; } length++; } return res; } }
Python3
class Solution: def countElements(self, arr: List[int]) -> int: res = 0 for num in arr: if num+1 in arr: res += 1 return res
class Solution: def countElements(self, arr: List[int]) -> int: s = set() res = 0 for x in arr: s.add(x) for x in arr: if x+1 in s: res += 1 return res
class Solution: def countElements(self, arr: List[int]) -> int: arr.sort() res = 0 length = 1 for i in range(1, len(arr)): if arr[i-1] != arr[i]: if arr[i-1] + 1 == arr[i]: res += length length = 0 length += 1 return res