Since it does not allow to sort the array, I assume it only asks for one triplet as solution or returns an empty triplet if no such sum exists. Also, I don't think using Hash map to store value to index works since the given array could have duplicates. I would recommend to use Hash map to store value to frequency.
vector<int> find3Sum(vector<int>& a, int target) {
int n = a.size();
if (n < 3) return vector<int>();
unordered_map<int,int> freq;
for (auto& x:a) freq[x]++;
for (int i = 0; i < n-1; i++) {
for (int j = i+1; j < n; j++) {
int residual = target - a[i] - a[j];
if (freq.count(residual)) {
int duplicity = 0;
if (residual == a[i]) duplicity++;
if (residual == a[j]) duplicity++;
if (freq[residual] > duplicity) return {a[i], a[j], residual};
O(N^2) 最坏情况[0,0,0,0,0] 是O(N^3)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i ++) {
map.put(nums, i);
}
for (int i = 0; i < nums.length-1; i ++) {
for (int j = i+1; j < nums.length; j ++) {
if (map.containsKey(-nums-nums[j])) {
if (map.get(-nums-nums[j]) > j) {
ArrayList<Integer> a = new ArrayList<>(Arrays.asList(nums, nums[j], nums[map.get(-nums-nums[j])]));
Collections.sort(a);
res.add(a);
}
}
}
}
res = res.stream().distinct().collect(Collectors.toList());
return res;
}
}