Stupid code!! but Accepted...Can anyone suggest me a better python code or Algo??

  • 0
    class Solution:
        # @return a tuple, (index1, index2)
        def twoSum(self, num, target):
            N = num
            num = sorted(num)
            i = 0
            for i in range(len(num) - 1):
                for j in range(i+1,len(num)):
                    if num[i]+num[j] == target:
                        s = N.index(num[i])+1
                        N[s - 1] = "aa"
                        k = N.index(num[j])+1
                        if (s > k):
                            [s,k] = (k,s)
                        return (s,k)
            return (0,0)

  • 3

    You can use a hashmap such that for key num[i], the value is i. And for a given num[i], find if (target-num[i]) exists in the map (and if so at what index). This approach is linear in runtime and memory. My solution for your reference:

    class Solution {
        vector<int> twoSum(vector<int> &numbers, int target) {
            unordered_map<int, int> map;
            vector<int> ans;
            for (unsigned i = 0; i < numbers.size(); ++i) {
                int other = target - numbers[i];
                unordered_map<int, int>::iterator found = map.find(other);
                if (found != map.end()) {
                map.insert(unordered_map<int, int>::value_type(numbers[i], i));
            return ans;

  • 0

    Just think in the python way,

    class Solution:
        # @return a tuple, (index1, index2)
        def twoSum(self, num, target):
            lookup = {}
            for idx, n in enumerate(num, 1):
                buddy = target - n
                if buddy in lookup:
                    return lookup[buddy], idx
                lookup[n] = idx

  • 0

    what time it cost if you use boost unordered_map?

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.