Given an array of integers A, return the largest integer that only occurs once.
If no integer occurs once, return -1.
Example 1:
Input: [5,7,3,9,4,9,8,3,1]
Output: 8
Explanation:
The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it's the answer.
Example 2:
Input: [9,9,8,8]
Output: -1
Explanation:
There is no number that occurs only once.
publicintlargestUniqueNumber(int[] A) {if (A ==null||A.length==0) {return-1; }// <num, freq>Map<Integer,Integer> numToCnt =newHashMap<>();for (int num : A) {numToCnt.put(num,numToCnt.getOrDefault(num,0) +1); }int max =-1;for (Map.Entry<Integer,Integer> entry :numToCnt.entrySet()) {if (entry.getValue() <2&&entry.getKey() > max) { max =Math.max(entry.getKey(), max); } }return max;}// solution sorting 解法,贴上来参考publicintlargestUniqueNumber(int[] A) {// Sort in ascending order.Arrays.sort(A);for (int i =A.length-1; i >=0; i--) {// If there is no duplicate return.if (i ==0||A[i] !=A[i -1]) returnA[i];// While duplicates exist.while (i >0&&A[i] ==A[i -1]) { i--; } }return-1;}