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
注意:这里是针对无序数组的,一般处理无序数组采用hashMap来保存数据,其中key保存数组中的值,value保存对应数组下标,因为key是不能有重复的,而value就可以重复。
而对于有序数组可以用两个指针来分别数组头和尾来进行查询。
package org.algorithm.leetcode;
import java.util.HashMap;
//two sum
public class Item1 {
//1、O(N)针对无序数组
public static int[] twoSum1(int[] nums, int target) {
int array[] = new int[100000];
int temp = 0;
for(int i = 0; i < nums.length; i++)
{
array[nums[i] + 5000] = i;
}
for(int i = 0; i < nums.length; i++)
{
temp = array[target - nums[i] + 5000];
if(temp >0 && temp > i)
return new int[]{i + 1, temp + 1};
}
return null;
}
//2、O(N)针对无序数组
public static int[] twoSum2(int[] nums, int target){
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
map.put(nums[i], i);
}
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
int j = map.get(temp);
if(j != i)
return new int[]{i+1,map.get(temp)+1};
}
}
return null;
}
//3、O(N)针对有序数组
public static int[] twoSum3(int[] nums,int target){
int i = 0;
int j = nums.length - 1;
while(i < j){
int temp = nums[i] + nums[j];
if(temp == target){
return new int[]{i+1,j+1};
}else if(temp > target){
j--;
}else{
i++;
}
}
return null;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}