返回

幸运数字的探索 -- LeetCode周赛182之Python、Java、C++实现

前端

幸运数字的定义

在整数数组中,如果一个整数的出现频次和它的数值大小相等,我们就称这个整数为「幸运数」。例如,在数组[2, 3, 2, 3, 2]中,2就是幸运数,因为它的出现频次为3,而它的数值大小也是3。

寻找幸运数字的步骤

  1. 首先,需要统计数组中每个元素出现的频次。您可以使用哈希表或字典来实现。
  2. 然后,遍历哈希表或字典,找到出现频次和数值大小相等的元素。
  3. 如果找到这样的元素,则将其作为幸运数并返回。
  4. 如果没有找到这样的元素,则返回-1。

Python实现

def findLucky(arr):
  """
  :type arr: List[int]
  :rtype: int
  """
  # 使用哈希表存储元素及其出现频次
  freq = {}
  for num in arr:
    if num not in freq:
      freq[num] = 0
    freq[num] += 1

  # 遍历哈希表,找到幸运数
  for num, freq in freq.items():
    if num == freq:
      return num

  # 如果没有找到幸运数,则返回-1
  return -1


# 测试代码
arr = [2, 3, 2, 3, 2]
result = findLucky(arr)
print(result)  # 输出:2

Java实现

import java.util.HashMap;
import java.util.Map;

class Solution {
    /**
     * Given an array of integers arr, find the largest integer such that its absolute difference with either of its neighbors is less than or equal to 1.
     *
     * @param arr The array of integers.
     * @return The largest integer that satisfies the condition.
     */
    public int findLucky(int[] arr) {
        // Create a hash map to store the frequency of each element in the array.
        Map<Integer, Integer> freqMap = new HashMap<>();

        // Populate the hash map with the frequencies of each element.
        for (int num : arr) {
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
        }

        // Find the largest integer that satisfies the condition.
        int maxLucky = -1;
        for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
            int num = entry.getKey();
            int freq = entry.getValue();

            if (num == freq && num > maxLucky) {
                maxLucky = num;
            }
        }

        // Return the largest lucky number.
        return maxLucky;
    }
}

C++实现

#include <iostream>
#include <unordered_map>
using namespace std;

class Solution {
public:
    int findLucky(vector<int>& arr) {
        // Create a hash map to store the frequency of each element in the array.
        unordered_map<int, int> freqMap;
        for (int num : arr) {
            freqMap[num]++;
        }

        // Find the largest integer that satisfies the condition.
        int maxLucky = -1;
        for (auto& [num, freq] : freqMap) {
            if (num == freq && num > maxLucky) {
                maxLucky = num;
            }
        }

        // Return the largest lucky number.
        return maxLucky;
    }
};

结语

在本篇文章中,我们介绍了如何寻找一个整数数组中的「幸运数」,并提供了Python、Java和C++的代码实现。我们希望这篇文章能够帮助您轻松理解幸运数的概念及其查找方法。如果您有任何问题或建议,请随时与我们联系。