File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed
algorithms/cpp/findTheDuplicateNumber Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ // Source : https://leetcode.com/problems/find-the-duplicate-number/
2+ // Author : Calinescu Valentin
3+ // Date : 2015-10-19
4+
5+ /* **************************************************************************************
6+ *
7+ * Given an array nums containing n + 1 integers where each integer is between 1 and
8+ * n (inclusive), prove that at least one duplicate number must exist.
9+ * Assume that there is only one duplicate number, find the duplicate one.
10+ *
11+ * Note:
12+ * You must not modify the array (assume the array is read only).
13+ * You must use only constant, O(1) extra space.
14+ * Your runtime complexity should be less than O(n2).
15+ * There is only one duplicate number in the array, but it could be repeated more than
16+ * once.
17+ * Credits:
18+ * Special thanks to @jianchao.li.fighter for adding this problem and creating all test
19+ * cases.
20+ *
21+ ***************************************************************************************/
22+
23+
24+
25+ /*
26+ * Solutions
27+ * =========
28+ *
29+ * A simple solution would be to sort the array and then look for equal consecutive elements.
30+ *
31+ * Time Complexity: O(N log N)
32+ * Space Complexity: O(1)
33+ *
34+ */
35+ #include < algorithm>
36+ class Solution {
37+ public:
38+ int findDuplicate (vector<int >& nums) {
39+ sort (nums.begin (), nums.end ());
40+ for (vector<int >::iterator it = nums.begin (); it != nums.end (); ++it)
41+ if (*it == *(it + 1 ))
42+ return *it;
43+ }
44+ };
You can’t perform that action at this time.
0 commit comments