I went to interview an iPad development company the other day. The first question was to find a duplicate number in 1000 (1-999. The 1000 numbers are sequential and out of order. My first reaction is to create an array of 999, and then find the corresponding array subscript based on the number. If it is null, it is filled, and if there is a value, it finds the number of duplicates. The Python version is as follows:
# Create test data, 1000 data records, and random sorting. 0-999 is used for simple purposes.
LST = range (1000) <br/> for I in range (500): <br/> pos1 = randint (0,999) <br/> pos2 = randint (0,999) <br/> lst [pos1], LST [pos2] = lst [pos2], LST [pos1. <br/> pos1 = randint (0,999) <br/> pos2 = randint (0,999) <br/> lst [pos1] = lst [pos2] <br/> Print 'Repeat number is: ', LST [pos1]
# Search using Arrays
Tmp_lst = [-1 for I in range (1000)] <br/> for N in lst: <br/> if n = tmp_lst [N]: <br/> Print 'method 1 find: ', n <br/> else: <br/> tmp_lst [N] = N
This method has the lowest time complexity, but the most complicated space. After the interview, I realized that the 1000-plus array (here lst) is actually a bucket. I don't need to create a temporary 1000 array. You only need to create a space to save the temporary number swap. The solution is also similar to the above, filling in the corresponding position according to the correspondence between numbers and the lower mark of the array. Every filling process is a series replacement process, such as an array like [, 3, 0]. After obtaining the first number 2, 3 in [2] is saved to the temporary variable, then [2] = 2, save 0 in [3] in the Temporary Variable [3] = 3, and then [0] = 0. This exchange process is complete.
Num =-1 <br/> Pos =-1 <br/> for I in range (1000 ): <br/> num = lst [I] <br/> # Skip if the subscript is the same as the value in it <br/> If I = num: <br/> continue <br/> else: <br/> while num! = I: <br/> If num = lst [num]: <br/> Pos = I <br/> Print 'method 2 find :', num <br/> Break <br/> lst [num], num = num, LST [num] <br/> lst [I] = num