数组中重复的数字

2021-09-02  本文已影响0人  EngineerPan

题目:
在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。

Input:
{2, 3, 1, 0, 2, 5}

Output:
2

答案

/// 解法一
func seekRepeat(nums: inout [Int]) -> Int {
    for element in nums {
        if element >= nums.count {
            return -1
          }
        }

    for i in 0 ..< (nums.count - 1) {
        for j in (i + 1) ..< nums.count {
            if nums[i] == nums[j] {
                return nums[i]
            }
        }
    }
    return -1
}

/// 解法二
func seekRepeat(nums: inout [Int]) -> Int {
    for i in 0 ..< nums.count {
        guard nums[i] < nums.count else { return -1 }
        while nums[i] != i {
            if nums[i] == nums[nums[i]] {
                return nums[i]
            }
            swap(nums: &nums, i: i, j: nums[i])
        }
    }
    return -1
}

func swap(nums: inout [Int], i: Int, j: Int) {
    let temp = nums[i]
    nums[i] = nums[j]
    nums[j] = temp
}
上一篇 下一篇

猜你喜欢

热点阅读