끄적끄적

[알고리즘] Two Sum(java, javascript) 본문

Computer Science/Algorithm

[알고리즘] Two Sum(java, javascript)

mashko 2020. 4. 25. 20:12
반응형

java

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

javascript

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    const comp = {};

    for (let i = 0; i < nums.length; i++){
        if (comp[nums[i] ]>=0){
            return [comp[nums[i] ] , i];
        }
        comp[target-nums[i]] = i;
    }
};
반응형
Comments