class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer[]}
def twoSum(self,nums, target):
"for array, if we would check whether some element is in the array, time complexity is O(n); while the dict would only take O(1)"
dic={}
for i in range(len(nums)):
if target-nums[i] not in dic:
dic[nums[i]]=i
else:
return min(i,dic.get(target-nums[i]))+1,max(i,dic.get(target-nums[i]))+1
"sort,left-><-right,O(nlogn) because of the sort algo"
"""
sortedNums=sorted(nums)
l,u=0,len(nums)-1
while l<u:
if sortedNums[l]+sortedNums[u]<target:
l+=1
elif sortedNums[l]+sortedNums[u]>target:
u-=1
else:
break
if u==l:
return -1,-1
p1=nums.index(sortedNums[l])+1
p2=nums.index(sortedNums[u])+1
if p1==p2:
p2=nums[p1:].index(sortedNums[u])+1+p1
return min(p1,p2), max(p1,p2)
"""
# @param {integer[]} nums
# @param {integer} target
# @return {integer[]}
def twoSum(self,nums, target):
"for array, if we would check whether some element is in the array, time complexity is O(n); while the dict would only take O(1)"
dic={}
for i in range(len(nums)):
if target-nums[i] not in dic:
dic[nums[i]]=i
else:
return min(i,dic.get(target-nums[i]))+1,max(i,dic.get(target-nums[i]))+1
"sort,left-><-right,O(nlogn) because of the sort algo"
"""
sortedNums=sorted(nums)
l,u=0,len(nums)-1
while l<u:
if sortedNums[l]+sortedNums[u]<target:
l+=1
elif sortedNums[l]+sortedNums[u]>target:
u-=1
else:
break
if u==l:
return -1,-1
p1=nums.index(sortedNums[l])+1
p2=nums.index(sortedNums[u])+1
if p1==p2:
p2=nums[p1:].index(sortedNums[u])+1+p1
return min(p1,p2), max(p1,p2)
"""
Brute force 暴力查找:
从目标字符串s的第一个字符起和模式串t的第一个字符进行比较,若相等,则继续逐个比较后续字符,否则从字符串的第二个字符起再重新和字符串t进行比较。以此类推,直至字符串t中的每个字符依次与字符串s的一个连续的字符序列相等,则称为模式匹配,此时字符串t的第一个字符在串s中的位置就是t在s中的起始位置,否则匹配不成功