当前位置: 移动技术网 > IT编程>开发语言>Java > LC#1

LC#1

2018年09月05日  | 移动技术网IT编程  | 我要评论

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数,且同样的元素不能被重复利用。

 1 class solution {
 2     public int[] twosum(int[] nums, int target) {
 3         map<integer,integer> map=new hashmap<>();
 4         for(int i=0;i<nums.length;i++){
 5             int x=target-nums[i];
 6             if(map.containskey(x)){
 7                 return new int[] {map.get(x),i};
 8             }
 9             map.put(nums[i],i);
10         }
11          throw new illegalargumentexception("no two sum solution");
12     }
13 }
14     }
15 }

 因为for循环可能导致无返回值时,可抛出异常解决。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网