FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/algorithms/cpp/missingNumber/MissingNumber.cpp at master · openhardnudd/leetcode · GitHub
openhardnudd
/
leetcode
Public
forked from
haoel/leetcode
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
algorithms
/
cpp
/
missingNumber
/
MissingNumber.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
54 lines (49 loc) · 1.78 KB
Breadcrumbs
leetcode
/
algorithms
/
cpp
/
missingNumber
/
MissingNumber.cpp
Copy path
File metadata and controls
54 lines (49 loc) · 1.78 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//
Source : https://leetcode.com/problems/missing-number/
//
Author : Hao Chen
//
Date : 2015-10-22
/*
**************************************************************************************
*
* Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the
* one that is missing from the array.
*
* For example,
* Given nums = [0, 1, 3] return 2.
*
* Note:
* Your algorithm should run in linear runtime complexity. Could you implement it using
* only constant extra space complexity?
*
* Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating
* all test cases.
*
**************************************************************************************
*/
class
Solution
{
public:
//
This problem can be converted to the classic problem --
//
`There is an array, all of numbers except one appears twice, and that one only appears once`
//
It means, we can combin two arrays together, one is [1..n], another one is `nums`.
//
Then, you know, we can use the XOR solve this problem.
int
missingNumber01
(vector<
int
>& nums) {
int
result =
0
;
for
(
int
i=
0
; i<nums.
size
(); i++){
result ^= nums[i];
}
for
(
int
i=
1
; i<=nums.
size
(); i++){
result ^=(i);
}
return
result;
}
//
We can simplify the previous solution as below
int
missingNumber02
(vector<
int
>& nums) {
int
result =
0
;
for
(
int
i=
0
; i<nums.
size
(); i++){
result = result ^ (i+
1
) ^ nums[i];
}
return
result;
}
int
missingNumber
(vector<
int
>& nums) {
//
By Leetcode running result, they all are same performance
return
missingNumber02
(nums);
//
36ms
return
missingNumber01
(nums);
//
36ms
}
};
Back
|
FazBrowse Home
|
New Git URL