返回介绍

solution / 1300-1399 / 1394.Find Lucky Integer in an Array / README_EN

发布于 2024-06-17 01:03:20 字数 3877 浏览 0 评论 0 收藏 0

1394. Find Lucky Integer in an Array

中文文档

Description

Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.

Return _the largest lucky integer in the array_. If there is no lucky integer return -1.

 

Example 1:

Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.

Example 2:

Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.

Example 3:

Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.

 

Constraints:

  • 1 <= arr.length <= 500
  • 1 <= arr[i] <= 500

Solutions

Solution 1: Counting

We can use a hash table or array $cnt$ to count the occurrences of each number in $arr$, then traverse $cnt$ to find the largest $x$ that satisfies $cnt[x] = x$. If there is no such $x$, return $-1$.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of $arr$.

class Solution:
  def findLucky(self, arr: List[int]) -> int:
    cnt = Counter(arr)
    ans = -1
    for x, v in cnt.items():
      if x == v and ans < x:
        ans = x
    return ans
class Solution {
  public int findLucky(int[] arr) {
    int[] cnt = new int[510];
    for (int x : cnt) {
      ++cnt[x];
    }
    int ans = -1;
    for (int x = 1; x < cnt.length; ++x) {
      if (cnt[x] == x) {
        ans = x;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int findLucky(vector<int>& arr) {
    int cnt[510];
    memset(cnt, 0, sizeof(cnt));
    for (int x : arr) {
      ++cnt[x];
    }
    int ans = -1;
    for (int x = 1; x < 510; ++x) {
      if (cnt[x] == x) {
        ans = x;
      }
    }
    return ans;
  }
};
func findLucky(arr []int) int {
  cnt := [510]int{}
  for _, x := range arr {
    cnt[x]++
  }
  ans := -1
  for x := 1; x < len(cnt); x++ {
    if cnt[x] == x {
      ans = x
    }
  }
  return ans
}
function findLucky(arr: number[]): number {
  const cnt = new Array(510).fill(0);
  for (const x of arr) {
    ++cnt[x];
  }
  let ans = -1;
  for (let x = 1; x < cnt.length; ++x) {
    if (cnt[x] === x) {
      ans = x;
    }
  }
  return ans;
}
class Solution {
  /**
   * @param Integer[] $arr
   * @return Integer
   */
  function findLucky($arr) {
    $max = -1;
    for ($i = 0; $i < count($arr); $i++) {
      $hashtable[$arr[$i]] += 1;
    }
    $keys = array_keys($hashtable);
    for ($j = 0; $j < count($keys); $j++) {
      if ($hashtable[$keys[$j]] == $keys[$j]) {
        $max = max($max, $keys[$j]);
      }
    }
    return $max;
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文