rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

1.两数之和 #2

Open Ni-Guvara opened 1 year ago

Ni-Guvara commented 1 year ago
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target)
    {        
        unordered_map<int,int>recd;
        for(int idx = 0;idx < nums.size();idx++)
        {
            auto it = recd.find(target - nums[idx]); 
            if( it != recd.end())
            {
                return {idx,it->second};
            }
            recd.insert({nums[idx],idx});
        }
        return {};
    }
};
rocksc30 commented 1 year ago

你代码提交的有问题

Ni-Guvara commented 1 year ago

哪有问题

rocksc30 commented 1 year ago

Java题解---HashMap标准解法

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(target - nums[i])){
                return new int[]{i, map.get(target - nums[i])};
            }
            map.put(nums[i], i);
        }
        return new int[]{};
    }
}
Ni-Guvara commented 1 year ago

加个java