1
+ Easy Leetcode 1394
2
+ tags : Array
3
+
4
+ 方法1 :
5
+ 题目不难 。最直观的解法
6
+ 方法2 :
7
+ 有点巧妙的解法 。排序之后又是从后往前遍历
8
+
9
+ 方法3
10
+ 用array存出现的次数 ,而不是hashmap 。这种情况index就是它的出现次数
11
+
12
+ Approach 3 A : Linked List (Beast Mode )
13
+
14
+ The idea is to use the input array to store counts . This approach , however , is quite tricky to implement correctly !
15
+
16
+ We can think of our array as a linked list , where arr [i ] points to arr [arr [i ] - 1 ] and so on , until the element that points to itself , or its outside of the array (and we do not care about that elements , per the intuition above ).
17
+
18
+ After we visit arr [arr [i ] - 1 ], we can use that element to track the count of arr [i ]. For the count , we will use a negative value to distinguish between pointers and counts .
19
+
20
+
21
+
22
+ ```
23
+
24
+ /*
25
+ 方法1
26
+ */
27
+ class Solution {
28
+ public int findLucky (int [] arr ) {
29
+ HashMap <Integer , Integer > map = new HashMap <>();
30
+ for (int i = 0 ; i < arr .length ; i ++) {
31
+ map .put (arr [i ], map .getOrDefault (arr [i ], 0 ) +1 );
32
+ }
33
+ int res = -1 ;
34
+ for (Map .Entry <Integer ,Integer > x :map .entrySet ()) {
35
+ if (x .getKey () == x .getValue ()) {
36
+ res = Math .max (res , x .getValue ());
37
+ }
38
+ }
39
+ return res ;
40
+ }
41
+ }
42
+
43
+ /*
44
+ 方法2
45
+ */
46
+ class Solution {
47
+ public int findLucky (int [] arr ) {
48
+ Arrays .sort (arr );
49
+ int count = 1 ;
50
+ for (int i = arr .length -2 ; i >=0 ; i --) {
51
+ if (arr [i ] == arr [i +1 ]) {
52
+ count ++;
53
+ }else {
54
+ if (count == arr [i +1 ]){
55
+ return count ;
56
+ }
57
+ count = 1 ;
58
+ }
59
+ }
60
+ return arr [0 ] == count ? count : -1 ;
61
+ }
62
+ }
63
+ /*
64
+ 方法3
65
+ */
66
+ class Solution {
67
+ public int findLucky (int [] arr ) {
68
+ int res = -1 ;
69
+
70
+ if (arr == null || arr .length == 0 )
71
+ return res ;
72
+
73
+ int [] store = new int [500 +1 ]; // if we read the Constraints, the max length is 500
74
+
75
+ for (int i = 0 ; i < arr .length ; i ++) {
76
+ store [arr [i ]]++; // increment each elements in the store arr
77
+ }
78
+
79
+ for (int i = store .length - 1 ; i >= 1 ; i --) { // iterate from the end
80
+ if (store [i ] == i ) // find the max element from the end, which equals condtions of the lucky integer
81
+ return store [i ];
82
+ }
83
+
84
+ return res ;
85
+ }
86
+ }
87
+
88
+
89
+
90
+ public static int findLucky (int [] arr ) {
91
+ for (int i = 0 ; i < arr .length ; i ++) {
92
+ int j = i , tmp = arr [i ];
93
+ while (tmp > 0 && tmp <= arr .length ) {
94
+ int val = arr [tmp -1 ];
95
+ arr [tmp -1 ] = Math .min (0 , arr [tmp -1 ]) -1 ;
96
+ if (tmp -1 <= i || tmp -1 == j ) {
97
+ break ;
98
+ }
99
+ j = tmp -1 ;
100
+ tmp = val ;
101
+ }
102
+ }
103
+ for (int i = arr .length ; i > 0 ; i --) {
104
+ if (-arr [i -1 ] == i ) {
105
+ return i ;
106
+ }
107
+ }
108
+ return -1 ;
109
+ }
0 commit comments