diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /find_duplicate_num.py | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'find_duplicate_num.py')
-rw-r--r-- | find_duplicate_num.py | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/find_duplicate_num.py b/find_duplicate_num.py new file mode 100644 index 0000000..f1d6170 --- /dev/null +++ b/find_duplicate_num.py @@ -0,0 +1,24 @@ +# 287. Find the Duplicate Number + +""" +given an integer array 'nums' containing 'n + 1' integers where each integer +is in the range '[1, n]' inclusive. there is only one repeated number in +'nums', return this repeated number. you must solve the problem without +modifying the array 'nums' and uses only constant extra space. +""" + + +class Solution(object): + def findDuplicate(self, nums): + for n in nums: + idx = abs(n) + if nums[idx] < 0: + return idx + nums[idx] = -nums[idx] + return len(nums) + + +if __name__ == "__main__": + obj = Solution() + print(obj.findDuplicate([1, 3, 4, 2, 2])) # expect: 2 + print(obj.findDuplicate([3, 1, 3, 4, 2])) # expect: 3 |