其他分享
首页 > 其他分享> > 两数之和

两数之和

作者:互联网

 1 import java.util.Arrays;
 2 
 3 public class Solution {
 4 
 5     public static void main(String[] args) {
 6         int[] arr = {2, 7, 11, 15};
 7         int ret[] = twoSum(arr, 9);
 8         System.out.println(Arrays.toString(ret));
 9     }
10 
11     public static int[] twoSum(int[] nums, int target) {
12         int n= nums.length;
13         for(int i=0;i<n;i++){
14             for(int j=i+1;j<n;j++){
15                 if(nums[i]+nums[j]==target){
16                     return new int[]{i,j};
17                 }
18             }
19         }
20         return new int[0];
21     }
22 }

 哈希表:

 1 import java.util.*;
 2 
 3 public class Solution {
 4 
 5     public static void main(String[] args) {
 6         int[] arr = {2, 7, 11, 15};
 7         int ret[] = twoSum(arr, 9);
 8         System.out.println(Arrays.toString(ret));
 9     }
10 
11     public static int[] twoSum(int[] nums, int target) {
12         Map<Integer,Integer>hashtable=new HashMap<Integer,Integer>();
13         for(int i=0;i<nums.length;i++){
14             if(hashtable.containsKey(target-nums[i])){
15                 return new int[]{hashtable.get(target-nums[i]),i};
16             }
17             hashtable.put(nums[i],i);
18         }
19         return new int[0];
20     }
21 }

 

标签:arr,int,ret,twoSum,static,public,两数
来源: https://www.cnblogs.com/miraiz/p/15547208.html