leetcode之Two Sum

举报
chenyu 发表于 2021/07/26 23:15:30 2021/07/26
【摘要】 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 ...

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


中文理解:给你一个数组,和一个目标值,数组里面任意2个元素的值之和等于目标值,然后返回这2个元素的下标,下标从一开始,不是0开始,上面的结果index1=1,index2=2就知道了
 


  
  1. public class Solution {
  2. public int[] twoSum(int[] nums, int target) {
  3. int index1=0;
  4. int index2=1;
  5. for(int i=0;i<nums.length;i++){
  6. for(int j=i+1;j<nums.length;j++){
  7. if(nums[i]+nums[j]==target){
  8. index1=i+1;
  9. index2=j+1;
  10. }
  11. }
  12. }
  13. int[] a=new int[2];
  14. a[0]=index1;
  15. a[1]=index2;
  16. return a;
  17. }
  18. }

 

 

 

文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/49493759

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。