Skip to content
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

只出现一次的数字 II #111

Open
louzhedong opened this issue Dec 20, 2018 · 0 comments
Open

只出现一次的数字 II #111

louzhedong opened this issue Dec 20, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处 LeetCode 算法第137题

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,3,2]
输出: 3

示例 2:

输入: [0,1,0,1,0,1,99]
输出: 99

思路

用一个map来保存访问的数字的次数

解答

var singleNumber = function (nums) {
  var map = {}
  for (var i = 0, length = nums.length; i < length; i++) {
    if (!map[nums[i]]) {
      map[nums[i]] = 1;
    } else {
      map[nums[i]]++;
    }
  }
  var res;
  Object.keys(map).forEach(key => {
    if (map[key] == 1) res = key;
  })

  return res;
};
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