# 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
# 你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
# 你可以按任意顺序返回答案。
# 示例 1:
# 输入:nums = [2,7,11,15], target = 9
# 输出:[0,1]
# 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1]
# 示例 2:
# 输入:nums = [3,2,4], target = 6
# 输出:[1,2]
# 示例 3:
# 输入:nums = [3,3], target = 6
# 输出:[0,1]
from typing import List
# class Solution:
# def twoSum(self, nums: List[int], target: int) -> List[int]:
# n = len(nums)
# for i in range(n):
# for j in range(i + 1, n):
# if nums[i] + nums[j] == target:
# return [i, j]
# return []
# 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 []
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# 遍历列表
for i in range(len(nums)):
# 计算需要找到的下一个目标数字
res = target - nums[i]
# 遍历剩下的元素,查找是否存在该数字
if res in nums[i + 1 :]:
# 若存在,返回答案。这里由于是两数之和,可采用.index()方法
# 获得目标元素在nums[i+1:]这个子数组中的索引后,还需加上i+1才是该元素在nums中的索引
return [i, nums[i + 1 :].index(res) + i + 1]
if __name__ == "__main__":
# # 创建Solution实例
# solution = Solution()
# # 定义测试用例
# test_cases = [
# {"nums": [2,7,11,15], "target": 9, "expected": [0,1]},
# {"nums": [3,2,4], "target": 6, "expected": [1,2]},
# {"nums": [3,3], "target": 6, "expected": [0,1]}
# ]
# # 执行测试用例
# for idx, case in enumerate(test_cases):
# nums = case["nums"]
# target = case["target"]
# expected = case["expected"]
# result = solution.twoSum(nums, target)
# print(f"测试用例{idx+1}:")
# print(f"输入: nums={nums}, target={target}")
# print(f"预期输出: {expected}")
# print(f"实际输出: {result}")
# print(f"测试结果: {'通过' if result == expected else '失败'}\n")
solution = Solution()
nums = [2, 7, 11, 15]
target = 9
res = solution.twoSum(nums, target)
print(res)
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
return new int[0];
}
}