LeetCode刷题——两数之和

简介: 两数之和

两数之和


来源:力扣(LeetCode)

链接:https://leetcode.cn/problems/two-sum


给定一个整数数组 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]


解答:

classSolution {
publicint[] twoSum(int[] nums, inttarget) {
int[] subscript=newint[2];
for(inti=0; i<nums.length; i++) {
for(intj=i+1; j<nums.length; j++) {
// 遍历数组,进行运算if(nums[i] +nums[j] ==target) {
subscript[0] =i;
subscript[1] =j;
break;
            }
            }
        }
returnsubscript;
    }
}




相关文章
|
19天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
19 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
1月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
1月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
1月前
|
存储
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
140 38
|
1月前
《LeetCode》——LeetCode刷题日记2
《LeetCode》——LeetCode刷题日记2
|
1月前
|
机器学习/深度学习 算法 索引
leetcode热题100.两数之和
leetcode热题100.两数之和
13 1
|
1月前
|
机器学习/深度学习 NoSQL Shell
力扣刷题-翻转字符串
力扣刷题-翻转字符串
11 1
|
1月前
|
存储
力扣刷题-最大子数组和
力扣刷题-最大子数组和
9 1
|
1月前
|
机器学习/深度学习 人工智能 算法
LeetCode刷题--- 面试题 01.07. 旋转矩阵(原地旋转+翻转替旋转)
LeetCode刷题--- 面试题 01.07. 旋转矩阵(原地旋转+翻转替旋转)