[LeetCode] 1. Two Sum 两数和

本文深入探讨了经典的“两数之和”算法问题,提供了多种解决方案,包括暴力解法和利用HashMap的高效解法。通过对比不同方法的时间复杂度,帮助读者理解算法优化的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 {};
}
};
内容概要:本文档详细介绍了基于MATLAB实现多目标差分进化(MODE)算法进行无人机三维路径规划的项目实例。项目旨在提升无人机在复杂三维环境中路径规划的精度、实时性、多目标协调处理能力、障碍物避让能力路径平滑性。通过引入多目标差分进化算法,项目解决了传统路径规划算法在动态环境多目标优化中的不足,实现了路径长度、飞行安全距离、能耗等多个目标的协调优化。文档涵盖了环境建模、路径编码、多目标优化策略、障碍物检测与避让、路径平滑处理等关键技术模块,并提供了部分MATLAB代码示例。 适合人群:具备一定编程基础,对无人机路径规划多目标优化算法感兴趣的科研人员、工程师研究生。 使用场景及目标:①适用于无人机在军事侦察、环境监测、灾害救援、物流运输、城市管理等领域的三维路径规划;②通过多目标差分进化算法,优化路径长度、飞行安全距离、能耗等多目标,提升无人机任务执行效率安全性;③解决动态环境变化、实时路径调整复杂障碍物避让等问题。 其他说明:项目采用模块化设计,便于集成不同的优化目标动态环境因素,支持后续算法升级与功能扩展。通过系统实现仿真实验验证,项目不仅提升了理论研究的实用价值,还为无人机智能自主飞行提供了技术基础。文档提供了详细的代码示例,有助于读者深入理解实践该项目。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值