LC-1
Two Sum
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have *exactly* one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
题解
- 双 for 循环
- for 循环 + HashMap,利用 containsKey 来处理 target - x 带来的一次 for 循环
Java实现,LC里面暴力双 for 执行用时更短。
package LC.hash;
import java.util.HashMap;
public class LC1 {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] res = twoSum(nums, target);
for (int item :
res) {
System.out.println(item);
}
}
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> integerHashMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (integerHashMap.containsKey(target - nums[i])) {
return new int[]{integerHashMap.get(target - nums[i]), i};
}
integerHashMap.put(nums[i], i);
}
return new int[0];
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i = 0; i < nums.length; i++){
for(int j = nums.length - 1; j > i; j--){
if(nums[i] + nums[j] == target){
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
}
Python实现
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[nums[i]] = i
return []
test_nums = [2, 7, 11, 15]
teat_target = 9
res = Solution()
print(res.twoSum(test_nums, teat_target))
# class C(object):
# @staticmethod
# def f():
# print('runoob');
#
#
# C.f(); # 静态方法无需实例化
# cobj = C()
# cobj.f() # 也可以实例化后调用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能