It seems that coding tests are conducted overseas in interviews with engineers, and in many cases, the main thing is to implement specific functions and classes according to the theme.
Apparently, many engineers take measures on the site called LetCode.
It is a site that trains the algorithmic power that can withstand the coding test that is being done in the early story, and it is an inevitable path for those who want to build a career at an overseas tech company.
I wrote it in a big way, but I have no plans to have such an interview at the moment.
However, as an IT engineer, it would be better to have the same level of algorithm power as a person, so I would like to solve the problem irregularly and write down the method I thought at that time as a memo.
I'm solving it with Python3.
Leet Code Table of Contents Starting from Zero
Last time Leet Code Day63 "195. Tenth Line" starting from zero
Right now, I'm prioritizing the Medium of the Top 100 Liked Questions. I solved all Easy, so if you are interested, please go to the table of contents.
Twitter I'm doing it.
** Technical Blog Started! !! ** ** I think the technology will write about LetCode, Django, Nuxt, and so on. ** This is faster to update **, so please bookmark it!
287. Find the Duplicate Number
The difficulty level is Medium. Excerpt from Top 100 Liked Questions.
The problem is, if given an array nums
containing n + 1 integers where each integer is between 1 and n, prove that there must be at least one duplicate number. ..
Design an algorithm that finds the number of duplicates, assuming that there is only one duplicate.
Example 1: Input: [1,3,4,2,2] Output: 2
Example 2: Input: [3,1,3,4,2] Output: 3
Note: Do not modify the array (assuming the array is read-only). Only the extra space of the constant O (1) must be used. The run-time complexity must be O (n2) or less. There is only one duplicate in the array, but it can be repeated multiple times.
Don't overlook the fact that it's read-only and can't be sorted.
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
low,high = nums[0],nums[nums[0]]
while low != high:
low,high = nums[low],nums[nums[high]]
low = 0
while low != high:
low,high = nums[low],nums[high]
return low
# Runtime: 64 ms, faster than 86.19% of Python3 online submissions for Find the Duplicate Number.
# Memory Usage: 16.4 MB, less than 35.59% of Python3 online submissions for Find the Duplicate Number.
Low is the answer by having each element with low
and high
and continuing to substitute the elements in nums by substituting 0 for low and repeating.
It may be a little unsatisfactory as a solution, but this time it is up to here. Thank you for your hard work.
Recommended Posts