Leet - 1

Having fun on Leetcode with C++, Java, Python & GO

Problem 1.Two Sum

My attempt(s)

Code

C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> answer(2,0);
        bool found=false;
        for (int i=0; i<nums.size()-1;i++){
            for (int j=i+1; j<nums.size();j++){
                if (nums[i]+nums[j]==target){
                    answer[0]=i;
                    answer[1]=j;
                    found=true;
                    break;
                }
                if (found)
                    break;
            }
            if (found)
                break;
        }
        return answer;
    }
};

Java

1
2
3
4
5
6
7
8
9
class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i=0; i<nums.length-1; i++)
            for (int j=i+1; j<nums.length; j++)
                if (nums[i]+nums[j]==target)
                    return new int[] {i,j};
        return new int[] {0,0};
    }
}

Python

1
2
3
4
5
6
7
8
class Solution(object):
    def twoSum(self, nums, target):
        for i in range(0,len(nums)-1,1):
            for j in range (i+1,len(nums),1):
                
                if nums[i]+nums[j]==target:
                    return [i,j]
        return []                

Explanation of idea

Good solution ref.

Code

Analysis

Licensed under CC BY-NC-SA 4.0