Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How LeetCode removes duplicates in a sorted array

Shulou Source: shulou.com Published: 2022-06-01 13:16:46 09月23日 Update

This article mainly introduces LeetCode how to delete the duplicates in the sorted array, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.

one

Topic description

Given a sorted array, you need to delete the repeating elements in place, make each element appear only once without using extra array space, and return the new length of the removed array. If you enter [1, 1, 1, 2], return 2.

two

Answer to the question

The topic requires that duplicate numbers be deleted in place, and no extra array space is used, so pay attention to the impact of changes in the length of the original array after deleting duplicate elements. Idea: two pointers point to the number you are currently looking for and the same number that follows it. When the latter number is the same as the current lookup number, delete the latter number, otherwise point to the next lookup number. Because the array is arranged in order, you do not need to traverse all the values after the current lookup number, as long as you find the first different value, you can complete this round of lookup. Class Solution: def removeDuplicates (self Nums: List [int])-> int: if len (nums) = = 0: return tmp = nums [0] iExhibit 1 while I < len (nums): if nums [I] = tmp: # Delete the value nums.pop (I) else: tmp somewhere in the list = nums [I] iDetection1 the above code is looked up from front to back You can also consider looking from back to front. When you encounter an ordered list search problem, it is necessary to establish a thought reflection of double pointers and search direction. Thank you for reading this article carefully. I hope the article "how to delete duplicates in the sorted array by LeetCode" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and follow the industry information channel. More related knowledge is waiting for you to learn!

Tags: Array number article sort element pointer order same in place point space length topic different original two code value location interest Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information MariaDB Huawei vpn Microsoft