码迷,mamicode.com
首页 > 其他好文 > 详细

1:Two Sum

时间:2015-03-05 23:30:51      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

java:

public int[] twoSum(int[] numbers, int target) {
        if(null!=numbers && numbers.length>0){
            int index1 =0,index2=0;
            boolean findResult = false;
            for(int i=0,len=numbers.length-1;i<len;i++){
                index1=i;
                for(int j=i+1,len2=numbers.length;j<len2;j++){
                    index2=j;
                    if(numbers[index1]+numbers[index2]==target){
                        findResult = true;
                        break;
                    }
                }
                if(findResult){
                    break;
                }
            }
            
            if(0!=index2){
                return new int[]{index1,index2};
            }
        }
        return null;
    }
    
    public int[] twoSum2(int[] numbers, int target) {
        
        int lenL = numbers.length/2;
        int lenR = numbers.length/2+1;
        
        if(numbers.length==2){
            lenL=0;
            lenR=1;
        }
        
        if(numbers[lenL]+numbers[lenR]==target){
            return new int[]{lenL,lenR};
        }else if(numbers[lenL]+numbers[lenR]>target){
            int [] numCopy = new int[lenR];
            System.arraycopy(numbers, 0, numCopy, 0, lenR);
            return this.twoSum2(numCopy, target);
        }else{
            int [] numCopy = new int[lenR];
            System.arraycopy(numbers, lenL, numCopy, 0, numbers.length-lenL);
            int [] numResult = this.twoSum2(numCopy, target);
            numResult[0]+=lenL;
            numResult[1]+=lenL;
            return numResult;
        }
        
    }

 

1:Two Sum

标签:

原文地址:http://www.cnblogs.com/shisw/p/4316871.html

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