File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .gatsby .offerII ;
2+
3+ import java .util .Arrays ;
4+ import java .util .HashMap ;
5+ import java .util .Map ;
6+
7+ /**
8+ * @author -- gatsby
9+ * @date -- 2022/7/13
10+ * @description -- 剑指 Offer II 004. 只出现一次的数字
11+ */
12+
13+
14+ public class _4OnlyOnce {
15+ public int singleNumber (int [] nums ) {
16+ Map <Integer , Integer > count = new HashMap <>();
17+ for (int num : nums ) {
18+ count .put (num , count .getOrDefault (num , 0 ) + 1 );
19+ }
20+
21+ for (int num : count .keySet ()) {
22+ if (count .get (num ) == 1 ) return num ;
23+ }
24+
25+ return -1 ;
26+ }
27+
28+ public int single (int start , int [] nums ) {
29+ return nums [start ] ^ nums [start + 1 ] ^ nums [start + 2 ];
30+ }
31+
32+ public int singleNumberSort (int [] nums ) {
33+ Arrays .sort (nums );
34+
35+ for (int i = 0 ; i + 3 < nums .length ; i += 3 ) {
36+ if (nums [i ] != nums [i +2 ]) return single (i , nums );
37+ }
38+ return -1 ;
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments