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

时间:2021-11-25 04:53:45

比如:

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

输出: index1=1, index2=2

 public class _003TwoSum {

     public static void main(String[] args) {
int a[]={3,22,4,7,8,22}; display(twoSum3(a,30));
}
  //暴力搜索法
public static int[] twoSum(int[] numbers, int target) {
int index[] = {0,0};
for(int i=0; i<numbers.length; i ++){
for(int j=i+1; j<numbers.length; j++){
if(target == numbers[i]+numbers[j]){
index[0] = i+1;
index[1] = j+1;
return index;
}
}
}
return index; } //使用map,因为刚好是两个值,一个值一个下表map刚好可以储存然后用map的containsKey的方法
public static int[] twoSum2(int[] numbers, int target) {
int index[] = {0,0};
HashMap<Integer, Integer> num = new HashMap<Integer,Integer>();
for(int i=0;i<numbers.length;i++){
num.put(numbers[i], i);
}
for(int i=0;i<numbers.length;i++){
int temp = target-numbers[i];
if(num.containsKey(temp)&&i<num.get(temp)){
index[0] = i+1;
index[1] = num.get(temp)+1;
break;
}
}
return index;
} public static void display(int a[])
{
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
} }