leetcode刷題記錄 easy(7) 961.N-Repeated Element in Size 2N Array

英文題目:

In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.

Return the element repeated N times.

Example 1:

Input: [1,2,3,3]
Output: 3

Example 2:

Input: [2,1,2,5,3,2]
Output: 2

Example 3:

Input: [5,1,5,2,5,3,5,4]
Output: 5

Note:

  1. 4 <= A.length <= 10000
  2. 0 <= A[i] < 10000
  3. A.length is even

中文題目解釋:

在一個A大小的數組中2N,有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

注意:

  1. 4 <= A.length <= 10000
  2. 0 <= A[i] < 10000
  3. A.length 爲偶數

解析:

遍歷數組A將值放入集合中,放入集合之前判斷集合中是否存在相同值,若已存在則返回該值

提交結果:

 

class Solution {
    public int repeatedNTimes(int[] A) {
        Set s=new HashSet();
        for (int i:A) {
            if(s.contains(i)){
                return i;
            }else{
                s.add(i);
            }
        }
        return 0;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章