Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc5d5a52

Browse files
Single Number
1 parent9640728 commitc5d5a52

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎MEDIUM/src/medium/SingleNumber.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
packagemedium;
2+
3+
importjava.util.HashSet;
4+
importjava.util.Iterator;
5+
importjava.util.Set;
6+
7+
/**136. Single Number QuestionEditorial Solution My Submissions
8+
Total Accepted: 141879
9+
Total Submissions: 277792
10+
Difficulty: Medium
11+
Given an array of integers, every element appears twice except for one. Find that single one.
12+
13+
Note:
14+
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
15+
16+
Hide Company Tags Palantir Airbnb
17+
Hide Tags Hash Table Bit Manipulation
18+
Hide Similar Problems (M) Single Number II (M) Single Number III (M) Missing Number (H) Find the Duplicate Number
19+
*/
20+
publicclassSingleNumber {
21+
//approach 1: use set, since this problem explicitly states that every element appears twice and only one appears once
22+
//so, we could safely remove the ones that are already in the set, O(n) time and O(n) space.
23+
//HashTable approach works similarly like this one, but it could be more easily extend to follow-up questions.
24+
publicintsingleNumber_using_set(int[]nums) {
25+
Set<Integer>set =newHashSet();
26+
for(inti :nums){
27+
if(!set.add(i))set.remove(i);
28+
}
29+
Iterator<Integer>it =set.iterator();
30+
returnit.next();
31+
}
32+
33+
34+
//approach 2: bit manipulation, use exclusive or ^ to solve this problem:
35+
//we're using the trick here: every number ^ itself will become zero, so, the only remaining element will be the one that
36+
//appeared only once.
37+
publicintsingleNumber_using_bit(int[]nums) {
38+
intres =0;
39+
for(inti :nums){
40+
res ^=i;
41+
}
42+
returnres;
43+
}
44+
45+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp