Skip to content

剑指 Offer 03. 数组中重复的数字 #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Geekhyt opened this issue Jul 26, 2021 · 0 comments
Open

剑指 Offer 03. 数组中重复的数字 #60

Geekhyt opened this issue Jul 26, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Jul 26, 2021

原题链接

借用 Map

题目要求我们找出数组中任意一个重复的数字,所以我们借助 Map 存储遍历过的数组,当遇到重复的数字时返回即可。

const findRepeatNumber = function(nums) {
    const map = new Map()
    for (let i of nums) {
        if (map.has(i)) return i
        map.set(i, true)
    }
    return null
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

原地交换

如果没有重复的数字,遍历完后,元素 i 应该在下标为 i 的位置。

1.遍历数组,如果当前元素值与 i 不相等,则将该元素与下标 i 对应位置的元素交换,直到相等。
2.如果元素值与下标 i 对应位置的元素相等,则是重复的,返回该元素即可。

const findRepeatNumber = function(nums) {
  for (let i = 0; i < nums.length; i++) {
    while (nums[i] != i) {
      if (nums[i] === nums[nums[i]]) return nums[i]
      let temp = nums[i]
      nums[i] = nums[temp]
      nums[temp] = temp
    }
  }
  return null
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
@Geekhyt Geekhyt added the 简单 label Jul 26, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant