码迷,mamicode.com
首页 > 其他好文 > 详细

1.两数之和

时间:2020-05-09 20:53:36      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:stat   on()   技术   opened   bsp   数组元素   图片   返回   获取   

技术图片

代码 :

技术图片
 1  public int[] twoSum(int[] nums, int target) {
 2           int[] a=new int[2];
 3             for(int i=0;i<nums.length;i++){
 4                 for (int j=i+1;j<nums.length;j++){
 5                     if (nums[i]+nums[j]==target){
 6                         a[0]=i;
 7                         a[1]=j;
 8                         return a;
 9                     }
10                 }
11             }
12         return a;
13     }
View Code

测试代码:

技术图片
 1 public class Solution {
 2 
 3     public int[] twoSum(int[] nums, int target) {
 4             int[] a=new int[2];
 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                         a[0]=i;
 9                         a[1]=j;
10                         return a;
11                     }
12                 }
13             }
14         return a;
15     }
16 
17     public static void main(String[] args) {
18         Solution solution=new Solution();
19         int[] nums={3,4,5,6,7};
20         int[] b=solution.twoSum(nums,9);
21         System.out.println(b[0]);
22         System.out.println(b[1]);
23     }
24 }
View Code

 

关键点:一维数组,双重for循环,if条件判断

思路:首先通过一层循环遍历数组元素,获取第一个元素值

   然后缩小遍历范围为(length-i),获取第二个元素值,

   然后与目标值进行比对,如果比对成功则将获取值的下标填充到新建数组中,

   最后将值返回。 

1.两数之和

标签:stat   on()   技术   opened   bsp   数组元素   图片   返回   获取   

原文地址:https://www.cnblogs.com/YoungSone/p/12859738.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!