Given an array of integers
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
nums
and an integer target
, return indices of the two numbers such that they add up to target
.You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Approach
Java
import java.util.Arrays;import java.util.HashMap;public class TwoSum {public static void main(String[] args) {int[] nums = { 2, 7, 11, 15 };int target = 9;int[] ans = twoSum(nums, target);System.out.println(Arrays.toString(ans));}private static int[] twoSum(int[] nums, int target) {HashMap<Integer, Integer> sorted = new HashMap<>();for (int i = 0; i < nums.length; i++) {sorted.put(nums[i], i);}for (int i = 0; i < nums.length; i++) {int cmp = target - nums[i];if (sorted.containsKey(cmp) && sorted.get(cmp) != i) {return new int[] { i, sorted.get(cmp) };}}return null;}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> twoSum(vector<int> &nums, int target){vector<pair<int, int>> v;for (int i = 0; i < nums.size(); i++)v.push_back({nums[i], i});//sort the arraysort(v.begin(), v.end());int i = 0, j = nums.size() - 1;vector<int> res;while (i < j){if ((v[i].first + v[j].first == target)){res.push_back(v[i].second);res.push_back(v[j].second);break;}else if (v[i].first + v[j].first > target)j--;elsei++;}sort(res.begin(), res.end());return res;}int main(){vector<int> nums = {2, 7, 11, 15};int target = 9;vector<int> ans = twoSum(nums, target);cout << "[" << ans[0] << "," << ans[1] << "]";return 0;}
No comments:
Post a Comment