File tree 5 files changed +83
-0
lines changed
longest-consecutive-sequence
5 files changed +83
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public boolean containsDuplicate (int [] nums ) {
3
+ HashSet <Integer > set = new HashSet <>();
4
+
5
+ for (int i = 0 ; i < nums .length ; i ++) {
6
+ if (set .contains (nums [i ])) {
7
+ return true ;
8
+ }
9
+ set .add (nums [i ]);
10
+ }
11
+ return false ;
12
+ }
13
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int rob (int [] nums ) {
3
+ if (nums .length == 0 ) return 0 ;
4
+ if (nums .length == 1 ) return nums [0 ];
5
+
6
+ nums [1 ] = Math .max (nums [0 ], nums [1 ]);
7
+
8
+ for (int i = 2 ; i < nums .length ; i ++) {
9
+ nums [i ] = Math .max (nums [i - 1 ], nums [i - 2 ] + nums [i ]);
10
+ }
11
+
12
+ return nums [nums .length - 1 ];
13
+ }
14
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int longestConsecutive (int [] nums ) {
3
+ int longest = 0 ;
4
+ Set <Integer > set = Arrays .stream (nums )
5
+ .boxed ()
6
+ .collect (Collectors .toSet ());
7
+
8
+ for (Integer i : set ) {
9
+ if (set .contains (i - 1 )) continue ;
10
+ int length = 1 ;
11
+
12
+ while (set .contains (i + 1 )) {
13
+ length ++;
14
+ i ++;
15
+ }
16
+ longest = Math .max (longest , length );
17
+ }
18
+ return longest ;
19
+ }
20
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public static int [] topKFrequent (int [] nums , int k ) {
3
+ Map <Integer , Integer > hashMap = new HashMap <>();
4
+ for (int i = 0 ; i < nums .length ; i ++) {
5
+ int num = nums [i ];
6
+ hashMap .put (num , hashMap .getOrDefault (num , 0 ) + 1 );
7
+ }
8
+
9
+ List <Integer > list = hashMap .entrySet ().stream ()
10
+ .sorted (Map .Entry .<Integer , Integer >comparingByValue ().reversed ())
11
+ .limit (k )
12
+ .map (Map .Entry ::getKey )
13
+ .toList ();
14
+
15
+ int [] result = list .stream ()
16
+ .mapToInt (Integer ::intValue )
17
+ .toArray ();
18
+
19
+ return result ;
20
+ }
21
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int [] twoSum (int [] nums , int target ) {
3
+ Map <Integer , Integer > hashMap = new HashMap <>();
4
+
5
+ for (int i = 0 ; i < nums .length ; i ++) {
6
+ int gap = target - nums [i ];
7
+ if (hashMap .containsKey (gap )){
8
+ int j = hashMap .get (gap );
9
+ return new int []{i ,j };
10
+ }
11
+ hashMap .put (nums [i ], i );
12
+ }
13
+ return null ;
14
+ }
15
+ }
You can’t perform that action at this time.
0 commit comments