Skip to content

LeetCode题解:137. 只出现一次的数字 II,排序后搜索,JavaScript,详细注释 #416

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
chencl1986 opened this issue Mar 16, 2023 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:
https://leetcode.cn/problems/single-number-ii/

解题思路:

  1. 将数组排序,除了只出现一次的数字,其他都是以3个一组的形式出现。
  2. 遍历数组,每次索引i指向的都是3个数字中的第1个。
  3. 如果nums[i]nums[i + 1]不相等,那么nums[i]只出现了一次。
  4. 如果nums[i]nums[i + 1]相等,那么查找下一组数字,即i = i + 3
/**
 * @param {number[]} nums
 * @return {number}
 */
var singleNumber = function (nums) {
  // 将数组排序
  nums.sort((a, b) => a - b)

  // 遍历nums,查找只出现1次的值
  // 如果相邻两个数字相同,那么nums[i]肯定出现了3次,下次从i+3位置开始搜索
  for (let i = 0; i < nums.length; i += 3) {
    // 如果遇到相邻两个数字不相等,nums[i]肯定只出现过一次
    if (nums[i] !== nums[i + 1]) {
      return nums[i]
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant