nums and an integer target, return indices of the two numbers such that they add up to target.
def twoSum(nums, target):
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return [lookup[target - num], i]
lookup[num] = i
def lengthOfLongestSubstring(s):
charSet = set()
left = 0
result = 0
for right in range(len(s)):
while s[right] in charSet:
charSet.remove(s[left])
left += 1
charSet.add(s[right])
result = max(result, right - left + 1)
return result
def reverseList(head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
a and an integer target, find indices of two elements whose sum is target. (Similar to LeetCode Two Sum)
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
vector<int> twoSum(vector<int>& a, int target) {
unordered_map<int,int> mp;
for(int i=0;i<a.size();++i) {
if(mp.count(target-a[i]))
return {mp[target-a[i]], i};
mp[a[i]] = i;
}
return {};
}