LeetCode | Two Sum

Algorithm 2019. 8. 21. 10:00
반응형

javascript 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function solution1(nums, target){
    console.log(nums, target);
    for(let i = 0; i<nums.length; i++){
        for(let j = i + 1; j<nums.length; j++){
            if( nums[i] + nums[j] === target){
                return [i, j];
            }
        }
    }
}
 
function solution2(nums, target){
    let dic = {};
    let result = [];
    for(let i = 0; i<nums.length; i++){
        let key = nums[i];
        dic[key] = i;
    }
 
    for(let i = 0; i<nums.length; i++){
        let key = target - nums[i];
        if(dic[key] !== undefined && dic[key] !== i){
            return [i, dic[key]];
        }
    }
}
 
//**** case1 ****
// let nums = [2,7,11,15];
// let target = 9;
 
//**** case2 ****
//let nums = [3,2,4];
//let target = 6;
 
//**** case3 ****
let nums = [2,5,5,11]
let target = 10;
 
// var result = solution1(nums, target);
 
var result = solution2(nums, target);
console.log(result);
 
 

 

 

c#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
    
    public int[] TwoSum(int[] nums, int target) {
        var dic = new Dictionary<intint>();
            
            for(int i = 0; i<nums.Length; i++){
                var num = nums[i];
                if(dic.TryGetValue(target - num, out int index)){
                    return new []{index, i};
                }
                dic[num] = i;
            }
 
            return null;
    }
}
 
 

 

https://codereview.stackexchange.com/questions/189999/two-sum-leetcode

 

Two Sum Leetcode

Looking for some feedback on the Two Sum LeetCode problem. Looking for feedback on code style in general, use of var, variable naming and initialization, return placement, and any other feedback or

codereview.stackexchange.com

 

반응형

'Algorithm' 카테고리의 다른 글

n사이에 소수 개수 구하기  (0) 2019.08.22
프로그래머스 | N개의 최소공배수  (0) 2019.08.22
베스트앨범  (0) 2019.08.20
위장  (0) 2019.08.20
전화번호 목록  (0) 2019.08.20
: