這個是來自力扣上的一道c++算法題目:
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,你不能重復利用這個數組中同樣的元素。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
自己采用的解法還有網上學習來的方法。
暴力方法:(遍歷每個元素 xx,並查找是否存在一個值與 target - xtarget−x 相等的目標元素。)
#include<iostream> using namespace std; int* twoSum(int nums[],int target) { int a[2]; for (int i = 0; i < (sizeof(nums)/4); i++) { for (int j = i + 1; j < (sizeof(nums)/4); j++) { for (int j = i + 1; j < (sizeof(nums)/4); j++) { if (nums[j] == target - nums[i]) { a[0]=i;a[1]=j; return a; } } } } int main() { cout<<"請輸入對應的數組 :"<<endl; int wen[],*wen2,q1; cin>>wen; cout<<"請輸入想要得到的數值 :"<<endl; cin>>q1; wen2=twoSum(wen,q1); cout<<"{"<<wen2[0]<<","<<wen2[1]<<"}"<<endl; return 0; }
然后就是關於哈希表的應用這種比較簡單:
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { return new int[] { i, map.get(complement) }; } } }
