Đề bài : Cho 1 mãng số nguyên dương và một số nguyên dương bất kỳ tìm vị trí các cặp phần tử trong mãng đó sao cho tổng của cặp phần tử đó bằng số nguyên dương đó.
Example :
Input a = [2,3,7,5,12,43,4,23,6] , target = 9
Output : [[0,2], [1,8], [3,6]]
Explain :
- a[0] = 2 , a[2] = 7 => a[0] + a[2] = 9 = target => [0,2]
- a[1] = 3 , a[8] = 6 => a[1] + a[8] = 9 = target => [1,8]
- a[3] = 5 , a[6] = 4 => a[3] + a[6] = 9 = target => [3,6]
=> Output : [[0,2], [1,8], [3,6]]
- Source Code :
import java.util.ArrayList;
import java.util.List;
public class TwoSum {
/*
* Example :
* Input a = [2,3,7,5,12,43,4,23,6] , target = 9
* Output : [[0,2], [1,8], [3,6]]
* Explain :
* - a[0] = 2 , a[2] = 7 => a[0] + a[2] = 9 = target => [0,2]
* - a[1] = 3 , a[8] = 6 => a[1] + a[8] = 9 = target => [1,8]
* - a[3] = 5 , a[6] = 4 => a[3] + a[6] = 9 = target => [3,6]
* => Output : [[0,2], [1,8], [3,6]]
*/
private static List<List<Integer>> solution1(int [] arr, int target){
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < arr.length -1; i++) {
if(arr[i] < target) {
for (int j = i + 1; j < arr.length; j++) {
if(arr[i] + arr[j] == target) {
List<Integer> indexs = new ArrayList<>();
indexs.add(i);
indexs.add(j);
result.add(indexs);
}
}
}
}
return result;
}
public static void main(String[] args) {
int [] arr = {2,3,7,5,12,43,4,23,6};
int target = 9;
System.out.println("Output 1 : " + TwoSum.solution1(arr, target));
int [] arr2 = {2,3,7,5,12,6,43,4,23,8,9};
int target2 = 15;
System.out.println("Output 2 : " + TwoSum.solution1(arr2, target2));
}
}
- Kết quả đạt được :