[算法學習]開始leetcode之旅

在此記錄一下用javascript刷leetcode的過程,天天都要堅持!javascript

1.Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.java

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.數組

Please note that your returned answers (both index1 and index2) are not zero-based.You may assume that each input would have exactly one solution.數據結構

Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2less

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    var len = nums.length,
        need,
        map = {},
        numbers = [];
    for(var i = 0; i < len; i++){
        need = target - nums[i];
        if(need in map){
            numbers.push(map[need] + 1);
            numbers.push(i + 1);
            break;
        }else{
            map[nums[i]] = i;
        }
    }
    return numbers;
};

這道題目注意下複雜度別傻傻的用雙循環...code

20.Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.ip

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    var len = s.length,
        cur,
        stack = [],
        map = {'(':')','[':']','{':'}'};
    for(var i = 0; i < len; i++) {
        cur = s[i];
        if(map.hasOwnProperty(cur)){
            stack.push(cur);
        }else{
            if(stack.length === 0){
                return false;
            }else{
                stackTop = stack.pop();
                if(map[stackTop] !== cur){
                    return false;
                }
            }
        }
    }
    if(stack.length === 0){
        return true;
    }else{
        return false;
    }
    
};

這道題目是利用堆棧的,比較巧妙,數據結構不少記不得了,最近抽時間多翻翻。ci

189.Rotate Array

Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].element

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    var len = nums.length;
    if(len === 0 || len === 1 || k===0){
        return;
    }
    var move = nums.splice(len - k,len);
    for(var i = move.length - 1;i >= 0;i--){
        nums.unshift(move[i]);
    }
};

這題用js寫的話就是考察下數組操做方法了,注意下特殊狀況便可。leetcode

相關文章
相關標籤/搜索