twoSum Algorithm : How to improve this?

前端 未结 22 2103
礼貌的吻别
礼貌的吻别 2021-02-06 01:38

I felt like doing an algorithm and found this problem on leetcode

Given an array of integers, find two numbers such that they add up to a specific target num

22条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-06 01:59

    An O(n) solution in c++ using hash map only exploiting Commutative rule of Addition in real numbers.

    class Solution {
    public:
        vector twoSum(vector& nums, int target) {
            unordered_map my_map;
              for ( int i = 0 ; i < nums.size(); i++ ){
                    if(my_map.find(target - nums[i]) != my_map.end()){
                        return vector {my_map[target - nums[i]], i};
                    }  
                    my_map[nums[i]] = i ;
              }
        }
    };
    

提交回复
热议问题