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

1. Two Sum I & II & III

时间:2016-07-19 09:36:44      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

1. Given an array of integers, return indices of the two numbers such that they add up to a specific target.

问题:

1.数组是否有序

2. 数组排序

// sorting array
   Arrays.sort(iArr)

方法1:O(n^2)

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++){
            for (int j = i+1; j < nums.length; j++){
                if(nums[i] + nums[j] == target){
                    result [0] = i;
                    result [1] = j;
                }
            }
        }
       return result; 
    }
}

 2. Two sum II  Input array is sorted (HashMap, 无相同元素

Given an array of integers that is already sorted in ascending order, 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.

 

 

public class Solution {
    public int[] twoSum(int[] nums, int target) {
int [] result = new int[2]; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++){ hm.put(nums[i], i); } for(int i = 0; i < nums.length; i++){ if(hm.containsKey(target-nums[i]) && target != 2 * nums[i]){ result[0] = i; result[1] = hm.get(target-nums[i]); break; } } return result; }
}

3. Two sum III  

 

1. Two Sum I & II & III

标签:

原文地址:http://www.cnblogs.com/beily/p/5683312.html

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