1 Two Sum

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) 
        """

 Brute force 暴力查找:

从目标字符串s的第一个字符起和模式串t的第一个字符进行比较,若相等,则继续逐个比较后续字符,否则从字符串的第二个字符起再重新和字符串t进行比较。以此类推,直至字符串t中的每个字符依次与字符串s的一个连续的字符序列相等,则称为模式匹配,此时字符串t的第一个字符在串s中的位置就是t在s中的起始位置,否则匹配不成功


            
        
            
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值