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

最大唯一数 #168

Open
louzhedong opened this issue Jul 27, 2019 · 0 comments
Open

最大唯一数 #168

louzhedong opened this issue Jul 27, 2019 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处 LeetCode 算法第5034题

给你一个整数数组 A,请找出并返回在该数组中仅出现一次的最大整数。

如果不存在这个只出现一次的整数,则返回 -1。

示例 1:

输入:[5,7,3,9,4,9,8,3,1]
输出:8
解释: 
数组中最大的整数是 9,但它在数组中重复出现了。而第二大的整数是 8,它只出现了一次,所以答案是 8。

示例 2:

输入:[9,9,8,8]
输出:-1
解释: 
数组中不存在仅出现一次的整数。

提示:

  1. 1 <= A.length <= 2000
  2. 0 <= A[i] <= 1000

思路

用一个map过滤掉所有出现多次的数字,对只出现一次的数字进行排序,输出最大的

解答

var largestUniqueNumber = function (A) {
  var map = {};
  A.map(function (item) {
    if (item in map) {
      map[item] = map[item]   1;
    } else {
      map[item] = 1;
    }
  });
  var array = [];
  for (var key in map) {
    if (map[key] == 1) {
      array.push(key);
    }
  }
  if (array.length == 0) {
    return -1;
  }
  array.sort(function (a, b) { return b - a });
  return array[0];
};

console.log(largestUniqueNumber([9,9,8,8]));
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