刪除排序數組中的重複項
- 給定一個排序數組,你需要在原地刪除重複出現的元素,使得每個元素只出現一次,返回移除後數組的新長度。
不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。
給定數組 nums = [1,1,2],
函數應該返回新的長度 2, 並且原數組 nums 的前兩個元素被修改爲 1, 2。
你不需要考慮數組中超出新長度後面的元素。
def func(nums):
res = [None]
for i in nums:
if i != res[-1]:
nums[len(res)-1] = i
res.append(i)
return len(res)-1
def func(nums):
if not (len(nums)):
return 0
i = 0
for j in range(1,len(nums)):
if (nums[j] != nums[i]):
i += 1
nums[i] = nums[j]
return i + 1
移除元素
- 給定一個數組 nums 和一個值 val,你需要原地移除所有數值等於 val 的元素,返回移除後數組的新長度。
不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。
元素的順序可以改變。你不需要考慮數組中超出新長度後面的元素
給定 nums = [3,2,2,3], val = 3,
函數應該返回新的長度 2, 並且 nums 中的前兩個元素均爲 2。
你不需要考慮數組中超出新長度後面的元素。
def func(nums,val):
for i in nums[:]:
if i == val:
nums.remove(i)
return len(nums)
實現 strStr
- 給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
輸入: haystack = "hello", needle = "ll"
輸出: 2
def func(haystack,needle):
if not needle:
return 0
return haystack.finnd(needle)
def func(haystack,needle):
res = -1
hlength = len(haystack)
nlength = len(needle)
length = hlength - nlength + 1
for i in range(length):
if haystack[i:i+nlength] == needle:
res = i
break
return res if needle else 0
搜索插入位置
- 給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。
你可以假設數組中無重複元素
輸入: [1,3,5,6], 5
輸出: 2
輸入: [1,3,5,6], 7
輸出: 4
def func(nums,target):
for i in range(len(nums)):
if nums[i] >= target:
return i
return len(nums)
# 二分法
def binary(nums,target):
size = len(nums)
if size == 0 or target > nums[-1]:
return size
left = 0
right = size - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
elif nums[mid] > target:
right = mid - 1
else:
return mid
return mid if nums[mid] > target else mid + 1