Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCood 算法题练习(一) #2

Open
yangfan0095 opened this issue May 4, 2018 · 0 comments
Open

LeetCood 算法题练习(一) #2

yangfan0095 opened this issue May 4, 2018 · 0 comments

Comments

@yangfan0095
Copy link
Owner

yangfan0095 commented May 4, 2018

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]


/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
let twoSum = function(nums, target) {
    let res = [];
    for (let i = 0; i < nums.length; i++) {
        let curTemp = isTarget(i, nums, target);
        if (curTemp > -1) {
            res.push(i);
            res.push(curTemp);
            break;
        }
    };
    return res;
};

let isTarget = (index, arr, target) => {
    let flag = -1;
    for (let i = index + 1; i < arr.length; i++) {
        if (arr[i] + arr[index] === target) {
            flag = i;
            break;
        }
    }
    return flag;
}
let nums = [2, 7, 11, 15],
    target = 9;
let result = twoSum(nums, target);
console.log(result);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant