1394. 找出数组中的幸运数『简单』

题目来源于力扣(LeetCode

一、题目

1394. 找出数组中的幸运数

题目相关标签:数组

提示:

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

二、解题思路

2.1 数组方式-哈希映射

  1. 因为题目已经给定数组元素的取值范围(且取值范围不算大)

  2. 创建取值范围长度的数组 nums

  3. 遍历 arr 数组,将数组元素作为索引,数值出现的次数作为数组元素

  4. 需要找到最大的幸运数,那么从后往前遍历nums 数组,第一个找到的幸运数则是最大的幸运数

三、代码实现

3.1 数组方式-哈希映射

public static int findLucky(int[] arr) {
    int[] nums = new int[501];
    // 遍历 arr 数组,将 arr 中各数组元素出现的次数记录在 nums 数组中
    for (int i = 0; i < arr.length; i++) {
        int j = arr[i];
        // arr 数组上的元素 = nums 索引值
        // arr 数组上各元素出现的次数 = nums 对应索引上元素的值
        nums[j]++;
    }
    // 从后往前遍历,即第一次出现的幸运数就是最大的幸运数
    for (int i = nums.length - 1; i > 0; i--) {
        if (i == nums[i]) {
            return i;
        }
    }
    return -1;
}

四、执行用时

4.1 数组方式-哈希映射

五、部分测试用例

public static void main(String[] args) {
//    int[] arr = {2, 2, 3, 4};  // output:2
//    int[] arr = {1, 2, 2, 3, 3, 3};  // output:3
//    int[] arr = {2, 2, 2, 3, 3};  // output:-1
//    int[] arr = {5};  // output:-1
    int[] arr = {7, 7, 7, 7, 7, 7, 7};  // output:7
    int result = findLucky(arr);
    System.out.println(result);
}
posted @ 2020-05-13 19:58  知音12138  阅读(214)  评论(0编辑  收藏  举报