Re: [闲聊] 每日LeetCode

楼主: umi0912umi (UMI)   2023-02-21 10:50:00
540. Single Element in a Sorted Array
题目:
给一个排列过的int阵列,里面的元素都正好出现2次,
除了某一元素只会出现一次,找出他并回传他的值,
需要在O(logn)时间及O(1)空间内完成
Example 1:
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: nums = [3,3,7,7,10,11,11]
Output: 10
思路:
应该要用二元搜寻做
但我直接用for
我就烂
因为nums[i]会等于nums[i+1]
直到单一的元素出现
找到他回传就好
=================================
python code :
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
n = len(nums)
for i in range(0, n, 2) :
if i+1 < n and nums[i+1] != nums[i] :
return nums[i]
return nums[i]
作者: Rushia (みけねこ的鼻屎)   2023-02-21 10:51:00
你时间复杂度没达标阿 等于没求得解
楼主: umi0912umi (UMI)   2023-02-21 10:59:00
不过这样也给过 好神奇XDDhttps://i.imgur.com/gtIS86N.png
作者: Rushia (みけねこ的鼻屎)   2023-02-21 11:01:00
LC有些题目本来就是因为有时间和空间复杂度限制才难

Links booklink

Contact Us: admin [ a t ] ucptt.com