LeetCode @ Two Sum D2F5

本文探讨了给定整数数组中寻找两个数使其和为目标值的问题,提出了暴力破解、哈希表及排序加双指针三种解决方案,并分析了各自的优缺点及时间复杂度。

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

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 (来源于:http://blog.youkuaiyun.com/linhuanmars/article/details/19711387

方法1:brute force时间复杂度为O(n^2), 对每一对pair两两比较。OJ超时!

public class Demo {
	
    public static int[] twoSum(int[] numbers, int target) {
        int[] res=new int[2];
        for(int i=0;i<numbers.length-1;i++){
            for(int j=i+1;j<numbers.length;j++){
                if(numbers[i]+numbers[j]==target){
                    res[0]=i;
                    res[1]=j;
                }
            }
        }
        return res;
    }
	public static void main(String[] args){
		 int[] numbers={2, 7, 11, 15};
		 int target=9;
		 int[] res=twoSum(numbers,target);
		System.out.println(res[0]+" "+res[1]);
	}
}

方法2:哈希表,存储每个数的下标。时间复杂度为O(n),同时空间复杂度也是O(n)。

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
	
        if(numbers==null || numbers.length<2)
            return null;
        
		int[] res=new int[2];
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); 
        for(int i=0;i<numbers.length;i++){
            if(map.containsKey(target-numbers[i])){//for的遍历已经获取了第一个数,所以if关注于(target减去第一个数)
                res[0]=map.get(target-numbers[i])+1;//get(),获取map的value【注意1】
                res[1]=i+1;
                return res;
            }
            map.put(numbers[i],i);
        }
        return null;
    }
}

【注意1】HashMap存取无续,所以res[]对应结果不一致。(是这样么,有待验证)

【注意2】把i数组的值存入Key,index存入Value。每个chain看作成若干EntryNode组成,每个Node有{int Key,int Value,EntryNode next}两个值和一个引用组成。

【后记】有个问题:[3,2,4],target=6;那么3+3=6是个问题么?

【后记】对HashMap还不理解深入,我的理解为地址值直接由底层算出hashVal(其实就是地址)得知,在O(1)时间可以获得;对比于array,需要遍历,只能在O(n)时间内获得。

方法3:先排序,然后左右夹逼 (来源于:http://blog.youkuaiyun.com/linhuanmars/article/details/19711387

先对数组进行排序,然后使用夹逼的方法找出pair。因为数组是有序的,有三种case:

(1)当前结果等于target,找到了pair;

(2)当前结果比target大,那么left右移只会使Sum更大,所以right左移

(3)当前结果比target小,那么right左移只会使Sum更小,所以left右移

所以每次只会有一个选择,从而实现线性就可以求出结果。该算法的时间复杂度是O(nlogn+n)=O(nlogn),空间复杂度取决于排序算法。

public int[] twoSum(int[] numbers, int target) {  
    int[] res = new int[2];  
    if(numbers==null || numbers.length<2)  
        return null;  
    Arrays.sort(numbers);  
    int left = 0;  
    int right = numbers.length-1;  
    while(left<right)   //不可能是 <=  
    {  
        if(numbers[left]+numbers[right]==target)  //case(1)
        {  
            res[0] = number[left];  
            res[1] = number[right];  
            return res;  
        }  
        else if(numbers[left]+numbers[right]>target)//case(2)
            right--; 
        else                                        //case(3)
            left++;  
    }  
    return null;  
} 

【后记1】返回的不是index,所以答案不对。方法是构造 一个数据结构,包含数字的值和index,然后排序。

【后记2】以上解法没有找到所有解,面试会要求找出所有解。




<think>好的,我现在需要帮助用户找到LeetCode中的第1题和第3题的链接,并确认它们属于哪个题库。首先,用户之前询问了关于转岗开发的学习计划,其中提到了LeetCode的题目编号,现在用户想知道这些题目的具体链接和所属题库。 首先,我需要回忆LeetCode的题目编号系统。LeetCode的题目是按照提交时间顺序编号的,所以题号是连续的。第1题通常是Two Sum,第3题是Longest Substring Without Repeating Characters。不过,用户可能会混淆不同的题库,比如中文版的力扣(LeetCode China)是否有不同的编号,但通常国际版和中文版的题目编号是一致的,只是标题翻译成中文。 接下来,我需要确认用户提到的题目是否确实是这两个。根据常见的LeetCode高频题目,这两个题号对应的题目是正确的。所以需要给出对应的链接。国际版和中文版的链接不同,用户可能在使用中文版,所以需要同时提供两种链接,或者询问用户是否需要中文版的链接。不过根据用户的工作背景,可能更倾向于国际版,但为了全面,应该都提供。 另外,用户可能不太清楚题目的具体内容,需要简要描述题目内容,以便用户理解为什么要刷这些题。例如,Two Sum是数组和哈希表的应用,而第三题涉及滑动窗口或双指针技巧,这些在车机开发中处理数据或算法时可能会用到。 还需要检查链接是否正确,避免给出错误的链接。例如,国际版的第1题链接是https://leetcode.com/problems/two-sum/,而中文版的是https://leetcode.cn/problems/two-sum/。同样的,第三题的国际版链接是https://leetcode.com/problems/longest-substring-without-repeating-characters/,中文版是https://leetcode.cn/problems/longest-substring-without-repeating-characters/。 另外,用户可能想知道这些题目属于哪个分类,比如数组、哈希表、字符串等,这样他们可以更有针对性地练习。例如,Two Sum属于数组和哈希表,第三题属于字符串和滑动窗口。 最后,需要确保回答清晰,结构合理,使用用户容易理解的语言,避免技术术语过多,同时保持专业性。可能需要用列表或格式化的方式呈现信息,让用户一目了然。 总结一下,回答需要包含以下几点: 1. 题目编号对应的题目名称。 2. 题目所属的LeetCode题库(国际版和中文版)。 3. 每个题目的简要描述和考察重点。 4. 对应的链接。 5. 解释为什么选择这些题目,与用户的学习计划相关。 现在需要将这些信息组织成自然的中文回答,确保准确性和有用性。</think>以下是LeetCode相关题目的详细信息整理: --- ### **LeetCode题目定位说明** #### **1. LeetCode #1** - **国际版标题**:`Two Sum` - **中文版标题**:`两数之和` - **所属分类**:数组 + 哈希表 - **题目链接**: - 国际版:https://leetcode.com/problems/two-sum/ - 中文版:https://leetcode.cn/problems/two-sum/ - **考察重点**: - 利用哈希表实现$O(n)$时间复杂度 - 数据索引与值的关系映射(车机开发中常用于状态快速查询) #### **2. LeetCode #3** - **国际版标题**:`Longest Substring Without Repeating Characters` - **中文版标题**:`无重复字符的最长子串` - **所属分类**:滑动窗口 + 字符串 - **题目链接**: - 国际版:https://leetcode.com/problems/longest-substring-without-repeating-characters/ - 中文版:https://leetcode.cn/problems/longest-substring-without-repeating-characters/ - **考察重点**: - 滑动窗口算法(车机轨迹线动态规划中常用类似思想) - 边界条件处理(与实时系统开发中的异常场景处理高度相关) --- ### **为什么选择这两题?** 1. **高频面试题**:90%以上车企/Tier1开发岗必考题型 2. **技能迁移性**: - `Two Sum` → 车机传感器数据匹配(如雷达点云快速索引) - `最长子串` → 视图系统事件流分析(如触控手势连续性判断) --- ### **题库版本说明** - **国际版**:题目更新更快,社区讨论更活跃(推荐优先使用) - **中文版**:题目描述为中文,适合英语阅读有障碍时参考 --- ### **下一步建议** ```mermaid graph TD A[完成题目] --> B[提交通过] B --> C{是否理解最优解?} C -->|是| D[尝试用C++11特性重构] C -->|否| E[参考官方题解] D --> F[关联Effective C++条款] F --> G[例如Item3: const优化变量声明] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值