讨论/《画解剑指 Offer》 - 剑指 Offer 03. 数组中重复的数字/
《画解剑指 Offer》 - 剑指 Offer 03. 数组中重复的数字
共 3 个回复

截屏2021-05-24 上午11.00.28.png

/**
 * @param {number[]} nums
 * @return {number}
 */
var findRepeatNumber = function(nums) {
    for(let i = 0; i < nums.length; i++){
        if(nums.indexOf(nums[i]) !== i){
            return nums[i];
        }
    }
    return -1;
};

笨办法

class Solution {
    public int findRepeatNumber(int[] nums) {
        int[] count = new int[nums.length];
        for(int i = 0;i < nums.length;i++){
            count[nums[i]]++;
        }
        int max = count[0];
        int maxj = 0;
        for(int j = 0;j < count.length;j++){
            if(max < count[j]){
                max = count[j];
                maxj = j;
            } 
        }
        return maxj;
    }
}

goby

class Solution:
    def findRepeatNumber(self, nums: List[int]) -> int:
        stat = dict()
        res = []
        for num in nums:
            if num in stat:
                return num
            else:
                stat[num] = 1
        return -1