码迷,mamicode.com
首页 > 编程语言 > 详细

找出数组中特定和数字下标(JAVA)

时间:2014-09-10 23:41:01      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   使用   java   ar   strong   for   

 

比如:

输入: numbers={2, 7, 11, 15}, target=9

输出: index1=1, index2=2

 

 

 1 public class _003TwoSum {
 2 
 3     public static void main(String[] args) {
 4         int a[]={3,22,4,7,8,22};
 5         
 6         display(twoSum3(a,30));
 7     }
 8       //暴力搜索法
 9      public static int[] twoSum(int[] numbers, int target) {
10           int index[] = {0,0};  
11             for(int i=0; i<numbers.length; i ++){  
12                 for(int j=i+1; j<numbers.length; j++){  
13                     if(target == numbers[i]+numbers[j]){  
14                         index[0] = i+1;  
15                         index[1] = j+1;  
16                         return index;  
17                     }  
18                 }  
19             }  
20             return index;  
21                 
22         }
23 
24      //使用map,因为刚好是两个值,一个值一个下表map刚好可以储存然后用map的containsKey的方法 
25      public static  int[] twoSum2(int[] numbers, int target) {
26             int index[] = {0,0};
27             HashMap<Integer, Integer> num = new HashMap<Integer,Integer>();
28             for(int i=0;i<numbers.length;i++){
29                 num.put(numbers[i], i);
30             }
31             for(int i=0;i<numbers.length;i++){
32                 int temp = target-numbers[i];
33                 if(num.containsKey(temp)&&i<num.get(temp)){
34                     index[0] = i+1;
35                     index[1] = num.get(temp)+1;
36                     break;
37                 }
38             }
39             return index;
40         }
41      
42      
43      public static void display(int a[])
44      {
45          for(int i=0;i<a.length;i++)
46              System.out.println(a[i]);
47      }
48      
49      
50    86 }

 

找出数组中特定和数字下标(JAVA)

标签:style   blog   color   os   使用   java   ar   strong   for   

原文地址:http://www.cnblogs.com/sweetculiji/p/3965290.html

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