I'm doing the leetcode question #217. Contains Duplicate. After checking the answer, I still cannot understand some parts of the code. The question is the following:
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
The answer is the following:
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
nums.sort()
for i in range(0,len(nums)-1):
if nums[i] == nums[i 1]:
return True
return False
The following is my question:
In my understanding, looping through range(0,len(nums)-1)
allows us to check and compare characters in num[0:-2]
, but what about the last two characters? How can we compare those two characters if we have nums
like [2,14,18,22,22]
. And for the last two lines, why can we directly use return False
instead of using the if...else...
structure? How is the logic be like here?
Thanks for anyone who can clarify my puzzle!
CodePudding user response:
You are comparing the last two elements. When i == len(nums)-2
, you compare nums[i]
with nums[i 1]
. Those are the last two elements.
You don't need if/else
. As soon as you find a duplicate, you immediately return from the function. So the only way to get to the end of the loop is if there are no duplicates.
CodePudding user response:
range(start, end, step
function work from start, start 1, start 2 ... end-1
, where end is exclusive and start is inclusive.
ie for range(0,100,1)
it wil go as 0,1,2,3,4,5......96,97,98,99
.
if your code you are checking character ith and(i 1)th character. so in at last index ie (len(num)-2)
, you are checking len(num)-2
and len(num)-1
character which include the last elements.
now why return directly false
. it is considering that all element are distinct if the program is reached till this statement. if any duplicate is found then it will be found in the for loop.