当前位置:网站首页>【每日一道LeetCode】——1. 两数之和
【每日一道LeetCode】——1. 两数之和
2022-08-02 02:36:00 【月亮嚼成星~】
目录
原题:两数之和
给定一个整数数组 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]
解题思路:
首先从数组的第一个元素开始,由于要比较两个数的和 目标数字是否相等,所以我们要利用循环,每次比较要比较数的后面的每一个数,看其和是否等于目标数字,如果相等就返回其下标,如果没有则不返回下标。
代码实现:
class Solution {
public int[] twoSum(int[] nums, int target) {
int length=nums.length;
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if(nums[i]+nums[j]==target){
return new int[]{i,j};
}
}
}
return new int[0];
}
}
执行结果:
总结:
每天都要刷,不可以懈怠!!!
边栏推荐
- 使用docker安装mysql
- nacos startup error, the database has been configured, stand-alone startup
- 详解最强分布式锁工具:Redisson
- The state status is displayed incorrectly after the openGauss switch
- 2022-08-01 mysql/stoonedb慢SQL-Q18分析
- NAS和私有云盘的区别?1篇文章说清楚
- analog IC layout-Design for reliability
- 很有意思的经历,很有意思的项目--文件夹对比工具
- Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community
- 线程的不同状态
猜你喜欢
EasyGBS平台播放视频时偶尔出现播放失败是什么原因?
2022河南青训联赛第(三)场
国标GB28181协议EasyGBS平台兼容老版本收流端口的功能实现
The failure to create a role in Dahua Westward Journey has been solved
ApiFox 基本使用教程(浅尝辄止,非广)
面对职场“毕业”,PM&PMO应该如何从容的应对?如何跳槽能够大幅度升职加薪?
Power button 1374. Generate each character string is an odd number
Flask 报错:WARNING This is a development server. Do not use it in a production deployment
永磁同步电机36问(三)——SVPWM代码实现
Remember a gorm transaction and debug to solve mysql deadlock
随机推荐
esp32经典蓝牙和单片机连接,,,手机蓝牙作为主机
Flask 报错:WARNING This is a development server. Do not use it in a production deployment
字典常用方法
Nanoprobes丨1-mercapto-(triethylene glycol) methyl ether functionalized gold nanoparticles
Use DBeaver for mysql data backup and recovery
60 Feature Engineering Operations: Using Custom Aggregate Functions【Favorites】
1688以图搜货
MySQL8 download, start, configure, verify
The first time I wrote a programming interview question for Niu Ke: input a string and return the letter with the most occurrences of the string
2022-08-01 Reflection
线程的不同状态
EasyGBS平台播放视频时偶尔出现播放失败是什么原因?
永磁同步电机36问(三)——SVPWM代码实现
指针数组和数组指针
2022 NPDP take an examination of how the results?How to query?
C#测试项目中属性的用法
ApiFox 基本使用教程(浅尝辄止,非广)
leetcode/字符串中的变位词-s1字符串的某个排列是s2的子串
忽晴忽雨
Service discovery of kubernetes