GithubHelp home page GithubHelp logo

algorithm's People

Contributors

jyzwf avatar

Stargazers

 avatar

Watchers

 avatar

algorithm's Issues

Two Sum

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]

暴力枚举:

/**
 * 
 * @param {Array} nums 
 * @param {Number} target 
 */
var twoSum = function (nums, target) {
	for (let i = 0, len = nums.length; i < len; i++) {
		for (let j = i + 1; j < len; j++) {
			if (nums[i] + nums[j] === target) {
				return [i, j]
			}
		}
	}
};

利用 hash 映射

/**
 * 
 * @param {Array} nums 
 * @param {Number} target 
 */
var twoSum = function (nums, target) {
	var len = nums.length;
	var hash = {};
	var i = 0;
	do {
		var a = nums[i];
		var j = hash[a];
		if (j !== undefined) {
			return [j, i];
		} else {
			hash[target - a] = i;
		}
	} while (++i < len);
};

console.log(twoSum([3, 2, 4, 5], 6))

image

Longest Substring Without Repeating Characters

description

Given a string, find the length of the longest substring without repeating characters.

example

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

解法1

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function (s) {
    let max = 0
    let tempMaxNoRepeateStr = '',
        finalMaxNoRepeateStr = ''
    for (let i = 0, len = s.length; i < len; i++) {
        let repeatePos = tempMaxNoRepeateStr.indexOf(s[i])
        if (repeatePos == -1) {
            tempMaxNoRepeateStr += s[i];
            if(max<=tempMaxNoRepeateStr.length){
                finalMaxNoRepeateStr = tempMaxNoRepeateStr
            }
        } else {
            let length = tempMaxNoRepeateStr.length;
            if (length > max) {
                max = length
                finalMaxNoRepeateStr = tempMaxNoRepeateStr
            }
            tempMaxNoRepeateStr = tempMaxNoRepeateStr.substring(repeatePos + 1) + s[i]
        }
    }

    return finalMaxNoRepeateStr.length
};

解法2

// 利用滑动窗口
var lengthOfLongestSubstring = function (s) {
    let len = s.length,
        max = 0,
        sumPos = 0
    if (len < 2) return len
    for (let i = 0, j = 1; j < len && i < j; j++) {
        let subStr = s.substring(i, j),
            strPos = subStr.indexOf(s[j])
        if (strPos == -1) {
            if (j - i + 1 > max) max = j - i + 1
        } else {
            if ((j - i) > max) max = j - i
            sumPos = i = strPos + sumPos + 1
        }
    }

    return max
}

Median of Two Sorted Arrays

description

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

coding

var findMedianSortedArrays = function (nums1, nums2) {
    let len1 = nums1.length,
        len2 = nums2.length

    let middlePos = parseInt((len1 + len2) / 2)  // 获取中间数位置

    let finalAry = [...nums1, ...nums2].sort((a, b) => a - b),
        middleNum
    if ((len1 + len2) % 2 == 0) {
        middleNum = (finalAry[middlePos] + finalAry[middlePos - 1]) / 2
    } else {
        middleNum = finalAry[middlePos]
    }

    return middleNum
};

求数组中未出现的最小正整数

问题描述:给定一个无序数列,求该数列中未出现的最小正整数

输入:[ -5 , 3 , 2 , 3 ]
输出:1

思路:
如果数组为 1,2,3,4,......N 且有序,那么它对应在数组中的存储结构如下:

0 1 2 3 ... N-1
1 2 3 4 ... N

那么 最小未出现的正整数为 N + 1,如果有比 N 大 或者比 N 小的数,就是不合法的数,也就有未出现的正整数一定在 1—N之间,由此我们可以有如下代码:

/**
 * 
 * @param {Array} arr 
 */

let findMinPositiveInt = (arr) => {
    let r = arr.length,
        l = 0;


    while (l < r) {
        if (arr[l] === l + 1) {
            l++
        } else if (arr[l] <= l || arr[l] > r || arr[arr[l] - 1] === arr[l]) {
            // 不合法数,比 r 大或者小,,这时候,最小正整数就在 [l+1 —— r-1] 中,
            // 最后一个判断 arr[arr[l] - 1] === arr[l] 是为了当元素不在自己应该在的位置,调整位置后,刚好该位置上的数已经是正确的数了,这时候,a[l]就是重复数,删除之
            arr[l] = arr[--r]
        } else {  // 合法,那么就将这个数摆到合理的位置,就是说 arr[i] 存 i+1
            swap(arr, l)
        }
    }

    return l + 1
}


/**
 * 
 * @param {Array} arr 
 * @param {Number} l 
 */

let swap = (arr, l) => {
    let temp = arr[l]
    arr[l] = arr[arr[l] - 1]
    arr[temp - 1] = temp
}

image

这时候 时间复杂度为 O(n)

ZigZag Conversion

Desc

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR"

解法1

var convert1 = function (s, numRows) {
    let zigzagCollection = new Array(numRows).fill('')
    let len = s.length,
        j = 0,
        _isForward = true   // 是否是正向

    if (numRows == 1) return 
    for (let i = 0; i < len; i++) {
        zigzagCollection[j] += s[i]

        if (j >= numRows - 1) {
            _isForward = false
        } else if (j <= 0) {
            _isForward = true
        }

        _isForward ? j++ : j--
    }

    return zigzagCollection
};

解法2

参考于 LeetCode 6. ZigZag Conversion

var convert2 = function (s, numRows) {
    if (s == null) return ''
    if (numRows == 1) return s

    var n = numRows * 2 - 2,
        array = new Array(numRows).fill('')

    for (let i in s) {
        let lineNumber = i % n
        if (lineNumber < numRows) {
            array[lineNumber] += s[i]
        } else {
            array[2 * numRows - lineNumber - 2] += s[i]
        }
    }

    return array.join('')
}

“马拉车”算法

今天刷leetcode时候,做求最大回文字串时,第一反应是暴力解决,分奇数和偶数,(算法太垃圾了-_-),但是不甘于这种解法,毕竟好学,所以就去google了,于是才发现有 马拉车算法 能线性解决这个问题,(原名:Manacher算法

要点

  1. 先将字符串变为 奇数 长度 --> 每个间隙和首尾添加特殊符号(不与字符串的字符相同)
  2. 回文串必定是中心对称的,也就是:S[i] == S[2id-i]

可怜的配图

  1. p[2 * id - i]>mx-i
    687474703a2f2f7777772e66656c69783032312e636f6d2f626c6f672f6174746163686d656e742f313331383437363238345f37393335346134372e706e67

  2. p[2 * id - i]<=mx-i
    687474703a2f2f7777772e66656c69783032312e636f6d2f626c6f672f6174746163686d656e742f313331383437383131345f34333739666235632e706e67

以下是 js 求解:

let logestPalindrome = function (s) {
    let p = [],
        mx = 0,
        id = 0

    let i

    let newStr = '#'
    let len = str.length
    for (i = 0; i < len; i++) {// 将字符串转化为奇数长度获取到新的字符串 
        newStr += str[i] + '#'
    }

    let newLen = newStr.length

    for (i = 0; i < newLen; i++) {
        p[i] = 0
    }

    for (i = 0; i < newLen; i++) { // 获取到所有的子回文的长度值组成的数组  
        p[i] = mx > i ? Math.min(p[2 * id - i], mx - i) : 1

        while ((newStr[i + p[i]] == newStr[i - p[i]]) && newStr[i + p[i]]) {// 超出其半径的位置再做额外判断,确保 newStr[i + p[i]] 是存在的  
            p[i]++
        }

        // 当有更大的回文串出现时,更新中心位置和最大边界值
        if (i + p[i] > mx) {
            id = i
            mx = id + p[i]
        }
    }

    return p        // 返回一个每个字符最大子串的数组
}

具体内容参考如下:
Manacher算法
最长回文子串

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.