1. 程式人生 > >LeetCode 961. 重複N次元素

LeetCode 961. 重複N次元素

基本思路

  1. 對A進行排序,遍歷A
  2. 記錄重複次數,滿足一半就返回;不滿足就重置計數
class Solution {
    public int repeatedNTimes(int[] A) {
        Arrays.sort(A);
        int ret = A[0];
        int num = 0;
        
        for(int i=0; i < A.length; i++){
            if(A[i] != ret){
                ret = A[i];
                num =
1; } else{ num++; if(num == A.length/2){ return ret; } } } return ret; } }

改進

最快速度是使用set,長度為A/2+1,當無法儲存時即此為結果

class Solution {
    public int repeatedNTimes(int[] A) {
        Set<
Integer>
set = new HashSet<>(A.length / 2 + 1); for (int i : A) { if (!set.add(i)) { return i; } } return 0; } }

由於有一半數肯定是相同的,只需要排序後判斷最後一個數和中間右是否相同,如果相同則後一半都為答案數,如果不同則中間左邊一位肯定是。

public int repeatedNTimes(int[] A) {
    Arrays.
sort(A); return A[A.length / 2] == A[A.length - 1] ? A[A.length - 1] : A[A.length / 2 - 1]; }
  • 此方法速度最慢,只是簡潔。