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.
假設,原題要求解可能有一組,這裏我們假設解有多組,只輸出第一組
public static int[] twoSum(int[] nums, int target) {
// write your code here
int[] index = new int[2];
int flag = 0;
for (int i = 0; i < nums.length-1; i++) {
for (int j = i+1; j < nums.length; j++) {
if(nums[i]+nums[j]==target){
index[0] = i+1;
index[1] = j+1;
}
}
}
return index;
}
這種做法可以輸出最後一組,如何在找到第一組解後結束循環呢?
public static int[] twoSum(int[] nums, int target) {
// write your code here
int[] index = new int[2];
int flag = 0;
for (int i = 0; i < nums.length-1; i++) {
for (int j = i+1; j < nums.length; j++) {
if(nums[i]+nums[j]==target){
index[0] = i+1;
index[1] = j+1;
flag = 1;
}if(flag == 1){
break;
}
}if(flag == 1){
break;
}
}
return index;
}
public static int[] twoSum(int[] nums, int target) {
// write your code here
int[] index = new int[2];
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
index[0] = i + 1;
index[1] = j + 1;
}
}
return index;
}
return index;
}
先排序:
public static void getSum(int[] array,int sum){
class innerClass{
int i;
int j;
public innerClass(int i, int j) {
this.i = i;
this.j = j;
}
}
ArrayList<innerClass> list = new ArrayList<>();
Arrays.sort(array);
int low = 0;
int high = array.length - 1;
while (low<high){
if(array[low]+array[high] == sum){
System.out.println("已找到");
list.add(new innerClass(low,high));
}
while (array[low]+array[high]>sum){
high--;
int temp = array[low]+array[high];
if(array[low]+array[high] == sum){
System.out.println("已找到");
list.add(new innerClass(low,high));
}
}
low++;
}
Iterator<innerClass> it = list.iterator();
while (it.hasNext()){
innerClass Result = it.next();
System.out.println(Result.i+" "+Result.j);
}
}
public static void getSumLow(int[] array,int target) {
int[] result = new int[2];
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();//聲明並指向一個HashMap集合的引用
for (int i = 0; i < array.length; i++) {//第一次遍歷數組,將元素和下標以K-V方式存入hm中
hm.put(array[i], i);
}
for(int i=0;i<array.length;i++) {//第二次遍歷數組,查找是否有和爲target的元素對
if (hm.containsKey(target - array[i]) && (i != hm.get(target - array[i]))) {
//保證兩個元素不是同一個,否則如果target恰好是某個元素的2倍時就不符合題意
//HashMap#boolean containsKey(Object key)
//HashMap#public V get(Object key){...return value;}
result[0] = i;
result[1] = hm.get(target - array[i]);
break;
}
}
System.out.print(result[0]+" "+result[1]);
}