[leetCode] - 1. Two Sum -
problem
https://leetcode.com/problems/two-sum/
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
solve
This problem is so simple and easy.
because, can use brute force!
![just compare for equality target , nums[i] + nums[i+1]](/_astro/01.BvKZUttV_Z1hs6UM.webp)
code
function twoSum(nums: number[], target: number): number[] {
let result:number[]|null = null;
//for loop twice
for(let i=0; i<nums.length; i++){
//if result is not null, previous calcurate find result
if(result){
break;
}
const c1 = nums[i];
for(let j=i+1; j<nums.length; j++){
const c2 = nums[j];
//if c1, c2 is same target, this caclurate done
if(c1 + c2 === target){
result = [i, j];
break;
}
}
}
return result;
};