题解 | #两数之和#利用列表的IndexOf求得数据元素的下标
两数之和
http://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
import java.util.*; public class Solution { /** * * @param numbers int整型一维数组 * @param target int整型 * @return int整型一维数组 */ public int[] twoSum (int[] numbers, int target) { ArrayList<Integer> al = new ArrayList<Integer>(numbers.length); int[] res = new int[2]; for(int x: numbers){ al.add(x); } for(int i = 0;i<numbers.length;i++){ int other = target -numbers[i]; int index = al.indexOf(other); if(index == -1 || index == i){ continue; }else{ if( i> index){ res[0] = index+1; res[1] = i+1; }else{ res[0] = i+1; res[1] = index+1; } break; } } return res; } }