TwoSum

注意:1.怎么至返回一次

         2.循环里使用al.remove,al.size()也会变

/*Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2*/
import java.util.*;

public class TwoSum {

    public static void main(String[] args) {
        // int[] nums= {3,2,4};
        int[] nums = { 3, 2, 4 };
        int[] arr = twoSum(nums, 6);
    }

    public static int[] twoSum(int[] nums, int target) {
        int[] arr = { 0, 0 };
        List<Integer> al = new ArrayList<Integer>();
        for (int i = 0; i < nums.length; i++)
            al.add(nums[i]);
        for (int i = 0; i < al.size(); i++) {
            if (al.contains(target - al.get(i))) {
                int index = al.indexOf(target - al.get(i));
                if (!(index == i))
                    {System.out.println("index1=" + (i + 1) + ", " + "index2="
                            + (index + 1));
                arr[0] = (i > index) ? index+1 : i+1;
                arr[1] = (i <= index) ? index+1 : i+1;
                return arr;}
            }
        }
        return arr;
    }

}
原文地址:https://www.cnblogs.com/kydnn/p/4551577.html