aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-07-04 18:49:43 -0600
committerJack Sangdahl <[email protected]>2025-07-04 18:49:43 -0600
commit321ae48f1860944804457bb0c8cc47ab0ebaaaec (patch)
tree166b937be6964aaa378b7137f286487ed026b226
parentcd518a4b7fb4fb8276751af7c0d7294389f34632 (diff)
downloadleetcode-321ae48f1860944804457bb0c8cc47ab0ebaaaec.tar.gz
leetcode-321ae48f1860944804457bb0c8cc47ab0ebaaaec.zip
1394. find lucky integer in an array
-rw-r--r--find_lucky_integer_array.c31
-rw-r--r--find_lucky_integer_array.py28
2 files changed, 59 insertions, 0 deletions
diff --git a/find_lucky_integer_array.c b/find_lucky_integer_array.c
new file mode 100644
index 0000000..f4fa1b4
--- /dev/null
+++ b/find_lucky_integer_array.c
@@ -0,0 +1,31 @@
+// 1394. Find Lucky Integer in an Array
+#include "leetcode.h"
+
+/*
+ * given an array of integers 'arr', a lucky integer is an integer equal 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 -, a lucky integer
+ * is an integer equal 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
+ */
+
+int findLucky(int *arr, int arrSize) {
+ for (int i = 0; i < arrSize; i++) {
+ arr[i] &= 0xFFFF;
+ int curr = arr[i];
+ if (curr <= arrSize)
+ arr[curr - 1] += 0x10000;
+ }
+ for (int i = arrSize; i > 0; --i)
+ if ((arr[i - 1] >> 16) == i)
+ return i;
+ return -1;
+}
+
+int main() {
+ int a1[] = {2, 2, 3, 4}, a2[] = {1, 2, 2, 3, 3, 3}, a3[] = {2, 2, 2, 3, 3};
+ printf("%d\n", findLucky(a1, ARRAY_SIZE(a1))); // expect: 2
+ printf("%d\n", findLucky(a2, ARRAY_SIZE(a2))); // expect: 3
+ printf("%d\n", findLucky(a3, ARRAY_SIZE(a3))); // expect: -1
+}
diff --git a/find_lucky_integer_array.py b/find_lucky_integer_array.py
new file mode 100644
index 0000000..078ea76
--- /dev/null
+++ b/find_lucky_integer_array.py
@@ -0,0 +1,28 @@
+# 1394. Find Lucky Integer in an Array
+from collections import Counter
+
+"""
+given an array of integers 'arr', a lucky integer is an integer equal 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 -, a lucky integer
+is an integer equal 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
+"""
+
+
+class Solution(object):
+ def findLucky(self, arr):
+ """
+ :type arr: List[int]
+ :rtype: int
+ """
+ cnt = Counter(arr)
+ return max([i for i, j in cnt.items() if i == j] + [-1])
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.findLucky(arr=[2, 2, 3, 4]))
+ print(obj.findLucky(arr=[1, 2, 2, 3, 3, 3]))
+ print(obj.findLucky(arr=[2, 2, 2, 3, 3]))