首页 > 其他 > 详细

TwoSum

时间:2015-06-04 15:31:00      阅读:253      评论:0      收藏:0      [点我收藏+]

注意: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;
    }

}

 

TwoSum

原文:http://www.cnblogs.com/kydnn/p/4551577.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!