SWIFT
two sum
//O(n) hashmaps C++ Two Sum leetcode
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> map;
for(int i=0; i<=nums.size();i++){
int compliment=target-nums[i];
if(map.count(compliment)==1){
return {map[compliment],i};
}
else{
map[nums[i]]=i;
}
}
return {-1,-1};
}
};
1. Two Sum
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> indices;
for(int i=0; i<nums.size(); i++) indices[nums[i]] = i;
for(int i=0; i<nums.size(); i++){
int left = target - nums[i];
if (indices.count(left) && indices[left]!=i) return {i, indices[left]};
}
return {};
}
};
two sum problem
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
for(int i = 0; i < len; i++) {
for(int j = i + 1; j < len; j++) {
if(nums[j] == target - nums[i])
return { i, j };
}
}
return {-1, -1};
};
two value sum
let x = 10
let y = 25
print("Sum of x and y = ", (x+y))
two sum problem
vector<int> twoSum(vector<int>& nums, int target) {
int front = 0, rear = nums.size() - 1;
sort(nums.begin(), nums.end());
while(front < rear) {
int sum = nums[front] + nums[rear];
if (sum == target)
break;
else if (sum > target)
rear--;
else
front++;
}
return {front, rear};
};
two sum solution
vector<int> twoSum(vector<int> &nums, int target){ // Brute Force Approach
for(int i = 0; i < nums.size(); i++){
for(int j = i+1; j < nums.size(); j++){
if(nums[i] + nums[j] == target){
vector<int> result;
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return vector<int>(); // return empty vector if no two sum solution
}
Two Sum
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
}
};
Two Sum
class Solution {
public int[] twoSum(int[] nums, int target) {
}
}
Two Sum
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
}
Two Sum
public class Solution {
public int[] TwoSum(int[] nums, int target) {
}
}
Two Sum
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
};
Two Sum
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
end
Two Sum
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
}
}
Two Sum
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum($nums, $target) {
}
}
Two Sum
function twoSum(nums: number[], target: number): number[] {
};