LEETCODE 0001

  1. Two Sum
    given nums = [2, 7, 11, 15], target = 9
    since nums[0] + nums[1] = 2 + 7 = 9
    return [0, 1]

PYTHON:

class Solution2(object):
def twoSum(self, nums, target):
“””
:type nums: List[int]
:type target: int
:rtype: List[int]
“””
lookup = {}
for i, num in enumerate(nums):
if target – num in lookup:
return [lookup[target – num], i]
lookup[num] = i
return []
def twoSum2(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    k = 0
    for i in nums:
        j = target - i
        k += 1
        tmp_nums = nums[k:]
        if j in tmp_nums:
            return [k - 1, tmp_nums.index(j) + k]

if name == ‘main‘:
print(Solution().twoSum((2, 7, 11, 15), 9))

class solution1(object):
def twosum(self, nums, target):
l = len(nums)
print(nums)
ans = []
for i in range(l – 1):
for j in range(i + 1, 1):
if nums[i] + nums[j] == target:
ans.append(i)
ans.append(j)
print([i, j])
break
return ans

JAVA:

SRC FILE: LeetCodeAnimation-master/No.1

class Solution {
public int[] twoSum(int[] nums, int target) {
int l = nums.length;
int[] ans=new int[2];
int i,j;
for(i=0;i<l-1;i++)
{
for(j=i+1;j<l;j++)
{
if(nums[i]+nums[j] == target)
{
ans[0]=i;
ans[1]=j;
}
}
}

    return ans;

}

}

C++:

SRC FILE: LEETCODE GRINDING GUIDE/PAGE9

vector twoSum(vector& numbers, int target) {
int l = 0, r = numbers.size() – 1, sum;
while (l < r) { sum = numbers[l] + numbers[r]; if (sum == target) break; if (sum < target) ++l; else –r; } return vector{l + 1, r + 1};
}

C:

SRC FILE: LeetCodeAnimation-master/No.1

int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int *ans=(int *)malloc(2 * sizeof(int));
int i,j;
bool flag=false;
for(i=0;i<numsSize-1;i++)
{
for(j=i+1;j<numsSize;j++)
{
if(nums[i]+nums[j] == target)
{
ans[0]=i;
ans[1]=j;
flag=true;
}
}
}
if(flag){
*returnSize = 2;
}
else{
*returnSize = 0;
}
return ans;
}
“`

from IPython.display import Image
Image(url=’C:\Users\YFL6\Desktop[999]FAMIINFO\AI MEDICINE\FUNCTIONS LIST[888]PROJECTS-LEETCODE\LeetCodeAnimation-master\0001-Two-Sum\Animation.gif’)

Leave a comment

Design a site like this with WordPress.com
Get started