Easy題目
題目鏈接
題目:
在大小為 2N 的數組 A 中有 N+1 個不同的元素,其中有一個元素重復了 N 次。
返回重復了 N 次的那個元素。
示例 1:
輸入:[1,2,3,3]
輸出:3
示例 2:
輸入:[2,1,2,5,3,2]
輸出:2
示例 3:
輸入:[5,1,5,2,5,3,5,4]
輸出:5
leetcode 5?提示:
4 <= A.length <= 10000
0 <= A[i] < 10000
A.length 為偶數
思路:很簡單很暴力,用hashmap記錄每個元素及其對應的出現次數,如果出現次數等于目標次數了,就直接返回… 后來一想,不一定非要等于目標次數,只要大于1就可以返回,速度果然快了很多。
class Solution {public int repeatedNTimes(int[] A) {int target = A.length / 2;Map<Integer, Integer> map = new HashMap<Integer, Integer>();for(int x : A){int count = map.getOrDefault(x, 0) + 1;map.put(x, count);if(count == target){return x;}}return 0;}
}
優化:
class Solution {public int repeatedNTimes(int[] A) {Map<Integer, Integer> map = new HashMap<Integer, Integer>();for(int x : A){int count = map.getOrDefault(x, 0) + 1;map.put(x, count);if(count > 1){return x;}}return 0;}
}
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态