Concept
In Python, elements in data types such as list,tuple can be duplicated, unlike set types (there are no duplicate elements in set). In this, there must be a corresponding algorithm to verify whether the sequence has duplicate elements.
Achieve a
def unique1 (S): for J
in
range (len (S)): for K in range (J + 1 , span class= "bu" >len (S)): if s[j] == S[k]: return false # found duplicate pair return true # if we reach this, elements were unique
The idea of implementing one is simple, and the outer loop iterates through each value in the sequence, from left to right. S[0] and s[1] ... S[N-1] [comparison], s[1] and s[2] ... S[n-1] is compared, until s[n-2] and s[n-1] are compared, then the traversal ends.
The number of comparisons mentioned above is (n-1) + (n-2) + ... + 2 + 1. Therefore, the total time complexity is O ($ n^2 $).
Implementation two
def unique2 (S): temp =
sorted
(S) for J in range (1 , len (temp)): if temp[j - 1 ] == temp[j]: return span class= "va" >false # found duplicate pair return true # if we reach this, elements were unique
As the code example shows, the first sort is sorted by Python's built-in sort function, by default, from small to large. If the same element exists in the sequence before sorting, the position of the same element is adjacent after sorting. For example, a = [5, 3, 2, 3, 4],b = sorted (a), then B = [2, 3, 3, 4, 5]. In this case, when iterating through a sequence, you only need to compare adjacent elements for equality. If you compare from left to right, there are no equal elements, the elements in the sequence are different.
- Built-in function sorted, which produces a copy of the original sequence after ordering. Its maximum time complexity is O (n$ \log $n). The time complexity of the sorting algorithm is analyzed separately.
- In a looping statement, the traversal sequence is n, and its time complexity is O (n). For this, the time complexity of the entire algorithm is O (n$ \log $n).
Sequence element cross-specific algorithm