1. Two Sum

网友投稿 647 2022-10-02

1. Two Sum

1. Two Sum

1. Two Sum

​​My Submissions​​

Question Editorial Solution

Total Accepted: 210007  Total Submissions: 937405  Difficulty: Easy

indices

exactly

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

UPDATE (2016/2/13): The return format had been changed to zero-based

74ms:

public class Solution { public int[] twoSum(int[] nums, int target) { int [] result=new int[2]; if(nums.length==2){ result[0]=0; result[1]=1; } if(nums.length>2){ for(int i=0;i

5ms:

public class Solution { public int[] twoSum(int[] nums, int target) { int[] nums_sorted=new int[nums.length]; System.arraycopy(nums,0,nums_sorted,0,nums.length); //Quicksort. Arrays.sort(nums_sorted); //Find the two numbers. O(n) int start=0; int end=nums_sorted.length; while(starttarget); if(nums_sorted[end]+nums_sorted[start]==target) break; while(nums_sorted[++start]+nums_sorted[end]

8ms:利用hash表

public class Solution {public static void main(String[] args) { int[] a = { 2, 7, 11, 15 }; System.out.println(twoSum(a, 9)); } public static int[] twoSum(int[] nums, int target) { int[] result = new int[2]; int n2; Integer idx; Map map = new HashMap(nums.length); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length - 1; i++) { n2 = target - nums[i]; idx = map.get(n2); if(idx != null && idx > i){ result[0] = i; result[1] = idx; break; } } return result; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:自学微信小程序从零到一:项目构建后http请求封装
下一篇:poj 1001 Exponentiation(大数)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~