Leetcode1 Two Sum

描述:给定一个数组,找出数组中两元素之和等于目标值,返回两数的索引。

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

1、暴力枚举法:
比较简单,也很容易想到。先固定外层循环中的i,再到内层循环查找是否有target-n存在。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]

2、哈希函数

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        num2idx = dict()
        for i, n in enumerate(nums):
            if target - n in num2idx:
                return num2idx[target - n], i
            else:
                num2idx[n] = i

3、双指针

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        tmp = []    
        for i in nums:
            tmp.append(i)        #对原数组备份
        nums = sorted(nums)      
        left = 0
        right = len(nums) - 1
        while (left < right):
            if nums[left] + nums[right] == target:
                break
            elif nums[left] + nums[right] < target:
                left += 1
            elif nums[left] + nums[right] > target:
                right -= 1
        res_a = nums[left]
        res_b = nums[right]
###########################想想设置a、b有什么作用?假如没有会怎样?############################
        left = -1      
        right = -1
        for i in range(0, len(tmp)):
            if tmp[i] == res_a and left == -1:
                left = i
            elif tmp[i] == res_b and right == -1:
                right = i
############################################################################################
#########################################交换a、b############################################
        if left > right:           
            left = left ^ right
            right = left ^ right
            left = left ^ right


        return [left, right]

思路:1)首先需要对数组进行拷贝,在对数组进行排序后,原数组的顺序已经完全打乱。
2)设置指针分别从首尾进行取数判断,并根据判断的结果决定进行左加还是右减。之后就是找到原索引,在这个过程中分别设置left=-1和right=-1是为了索引的时候不会相互影响。以[3, 3]为例,如果没有tmp[i] == res_a and left == -1的判断,最后的输出结果将是[1, 1]。当i=0时,left = i =0(不太科学,没想到怎么表示);当i=1时,虽然tmp[1] = res_a但是left != -1就会直接逃过而执行elif
参考:https://www.cnblogs.com/kirai/p/5597144.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值