[LeetCode] 1. 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].

给一个包含整数的数组,找出使得两个数的和是给定值的indices(索引,下标)。假设每个输入只有一个答案, 同一元素不会用到两次。

解法:

  1. 暴力解法,两个for循环遍历,两个数相加和目标数比较。Time: O(n^2)

  2. 先遍历一遍数组,建立数字和index的HashMap,然后再遍历一遍,开始查找target - num[i]是否在map中,如果在,找到并返回index。Time: O(n) Space: O(n)

Java:解法1

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res=new int[2];
        for(int i=0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;++j){
                if(nums[i]+nums[j]==target){
                    res[0]=i;
                    res[1]=j;
                }
            }
        }
        return res;
    }
}

Java:解法2

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer>hashmap=new HashMap<Integer,Integer>();
        int[]res=new int[2];
        for(int i=0;i<nums.length;++i)
            hashmap.put(nums[i],i);
        for(int i=0;i<nums.length;++i){
            int temp=target-nums[i];
            if(hashmap.containsKey(temp) && hashmap.get(temp)!=i){
                res[0]=i;
                res[1]=hashmap.get(temp);
            }
        }
        return res;
    }
}

Java:解法2

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> m = new HashMap<Integer,Integer>();
        int[]res=new int[2];
        for(int i=0;i<nums.length;++i){
            if(m.containsKey(target-nums[i])){
                res[0]=i;
                res[1]=m.get(target-nums[i]);
                break;
            }
            m.put(nums[i],i);
        }
        return res;
    }
}

Python:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        
        hash_map={}
        for i,value in enumerate(nums):
            hash_map[value]=i
        for index1,value in enumerate(nums):
            if target-value in hash_map: 
                index2=hash_map[target-value]
                if index1!=index2:
                    return index1,index2 
知识点:enumerate
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
print(list(enumerate(seasons,start=1)))# 下标从1开始 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
"""
普通的for循环
"""
seq = ['one', 'two', 'three']
for i in range(len(seq)):
    print(seq[i])
"""
for 循环使用enumerate
"""
for index,element in enumerate(seq):
    print(index,element)
    
知识点:集合
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # 这里演示的是去重功能  {'apple', 'banana', 'pear', 'orange'}
print('orange' in basket)# 快速判断元素是否在集合内  True
                     

Python:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        map={}
        for index,value in enumerate(nums):
            if target-value in map:
                return index,map[target-value] # 交换也可以
            map[value]=index

Python:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        map={}
        for index in range(len(nums)):
            if target-nums[index] in map:
                return index,map[target-nums[index]]
            map[nums[index]]=index

Python:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums)<=1:
            return False
        buff_dict={}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return buff_dict[nums[i]],i
            buff_dict[target-nums[i]]=i
        
        

python:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
       unordered_map<int,int> lookup;
       for(int i=0;i<nums.size();++i){
           if(lookup.count(target-nums[i])){
              return {lookup[target-nums[i]],i}; 
           }   
           lookup[nums[i]]=i;
       }
       return {};
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值