【LeetCode】Basic Algorithm Questions

  1. sum of two numbers

Given an integer array nums and an integer target value target, please find the two integers whose sum is the target value target in the array, and return their array subscripts.
You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer.
You can return answers in any order.
Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, return [0, 1].

Problem-solving ideas:
(1) Violent enumeration: enumerate each number x in the array, and find whether target-x exists in the array
(2) Hash table: We create a hash table. For each x, we first Query whether target - x exists in the hash table, and then insert x into the hash table to ensure that x will not match itself.

var twoSum = function(nums, target) {
    
    
	//暴力枚举方法1
    /*for(let i=0;i<nums.length-1;i++){
        for(let j=i+1; j<nums.length;j++){
            if(target === nums[i]+nums[j]) return [i,j]
        }
    }*/
    //暴力枚举方法2
    for(let i=0;i<nums.length;i++){
    
    
        let temp = target - nums[i]
        let j = nums.indexOf(temp)
        if(j != -1 && j != i) return [i,j]    
    }
    return [-1, -1]
};
var twoSum = function(nums, target) {
    
    
    let hashTable = {
    
    }
    for(let i=0; i<nums.length; i++){
    
    
        let temp = target-nums[i]
        // if(hashTable.hasOwnProperty(temp)) {
    
    
        if(temp in hashTable) {
    
    
            return [hashTable[temp], i]
        }     
        hashTable[nums[i]] = i
    }
    return []
};
  1. Palindrome

Given an integer x, return true if x is a palindrome; otherwise, return false
.
For example, 121 is a palindrome, but 123 is not.

Problem-solving ideas:
(1) Convert it into a string, and gradually judge whether the numbers before and after are equal
(2) Reverse the number itself, and then compare the reversed number with the original number. If they are the same, then the number is palindrome.

var isPalindrome = function(x) {
    
    
    //1.基础方法  转成字符串,遍历进行判断
    let s = x.toString().split('')
    for(let i=0; i<s.length/2;i++){
    
    
        if(s[i] != s[s.length-1-i]) return false
    }
    return true 

var isPalindrome = function(x) {
    
    
    //2.官方算法思路  反转数字进行判断
    // (1)负数和最后一位数字为0(0除外)的肯定不是回文数
    if(x === 0) return true
    if(x < 0 || x % 10 === 0) return false

    //(2)从后往前取除以10的商和余数,计算反转后的数,当反转后的数大于等于商时,就取完了一半的数,可以停止了
    let quotient = x
    let remainder = 0
    let revert = 0
    while(revert < quotient){
    
    
        remainder = quotient % 10
        quotient = Math.floor(quotient / 10)
        revert = revert * 10 + remainder
        // console.log(remainder, quotient, revert)
    }
    //这一步之前没想到
    if(revert === quotient || quotient === Math.floor(revert / 10)) return true
    return false
};

official solution

var isPalindrome = function(x: number): boolean {
    
    
    // 特殊情况:
    // 如上所述,当 x < 0 时,x 不是回文数。
    // 同样地,如果数字的最后一位是 0,为了使该数字为回文,
    // 则其第一位数字也应该是 0
    // 只有 0 满足这一属性
    if (x < 0 || (x % 10 === 0 && x !== 0)) {
    
    
        return false;
    }

    let revertedNumber: number = 0;
    while (x > revertedNumber) {
    
    
        revertedNumber = revertedNumber * 10 + x % 10;
        x = Math.floor(x / 10);
    }

    // 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。
    // 例如,当输入为 12321 时,在 while 循环的末尾我们可以得到 x = 12,revertedNumber = 123,
    // 由于处于中位的数字不影响回文(它总是与自己相等),所以我们可以简单地将其去除。
    return x === revertedNumber || x === Math.floor(revertedNumber / 10);
};
  1. Convert Roman Numerals to Integers

Roman numerals contain the following seven characters: I, V, X, L, C, D, and M.
Character value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, the Roman numeral 2 is written as II, that is, two parallel 1s. 12 written as XII is X + II. 27 is written as XXVII, which is XX + V + II.
Normally, the smaller digits in Roman numerals are to the right of the larger digits. But there are also special cases, for example, 4 is not written as IIII, but IV. The number 1 is on the left of the number 5, and the represented number is equal to the value 4 obtained by reducing the number 1 from the large number 5. Likewise, the number 9 is expressed as IX. This special rule applies only to the following six cases:
I can be placed to the left of V (5) and X (10) to represent 4 and 9.
X can be placed to the left of L (50) and C (100) to represent 40 and 90.
C can be placed to the left of D (500) and M (1000) to represent 400 and 900.
Given a Roman numeral, convert it to an integer.
Example 1:
Input: s = “III”
Output: 3
Example 2:
Input: s = “IV”
Output: 4

Problem-solving ideas:
(1) Traverse the string, first calculate and replace the six special cases with empty ones, and then calculate the normal cases
(2) When traversing, perform addition and subtraction of the previous digit, if the previous digit is less than the standard digit, the sum up and down, otherwise up

// @lc code=start
/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    
    
    let objSpecial = {
    
    
        'IV': 4,
        'IX': 9,
        'XL': 40,
        'XC': 90,
        'CD': 400,
        'CM': 900,
    }
    let objNormal = {
    
    
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }

    // 方法一
     let str = s
     //获取字符串中特殊的字符
     let sum = 0
     Object.entries(objSpecial).forEach(([key, value]) => {
    
    
         let num = 0
         let index = str.indexOf(key)
         while(index != -1) {
    
    
             num += 1
             str = str.replace(key,'')
             index = str.indexOf(key)
         }
         sum += num*value
     });
     Object.entries(objNormal).forEach(([key, value]) => {
    
    
         let num = 0
         let index = str.indexOf(key)
         while(index != -1) {
    
    
             num += 1
             str = str.replace(key,'')
             index = str.indexOf(key)
         }
         sum += num*value
    });
    // // console.log(sum);
    return sum

};
// @lc code=start
/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    
    
    let objSpecial = {
    
    
        'IV': 4,
        'IX': 9,
        'XL': 40,
        'XC': 90,
        'CD': 400,
        'CM': 900,
    }
    let objNormal = {
    
    
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }

    //方法二-多判断一位,右边大于左边就减,否则就加
    let sum = 0
    let pre = ''
    for (let i=0; i< s.length; i++){
    
    
        if(pre == '') {
    
    
            pre = s[i]
            continue
        }
        if(objNormal[s[i]] > objNormal[pre]){
    
    
            sum -= objNormal[pre]
        }
        else{
    
    
            sum += objNormal[pre]
        }
        pre = s[i]
    }
    sum += objNormal[s[s.length-1]]
    return sum

};
  1. longest common prefix

Write a function to find the longest common prefix in an array of strings.
Returns the empty string "" if no common prefix exists.
Example 1:
Input: strs = ["flower", "flow", "flight"]
Output: "fl"
Example 2:
Input: strs = ["dog", "racecar", "car"]
Output: ""
Explanation : No common prefix exists for the input.

Problem-solving idea:
first obtain the minimum length of all strings, traverse the strings separately, and save the characters corresponding to the index in an array. If all elements of the array are the same, splice the common prefix and execute the next cycle , otherwise exit the loop and return the result

// @lc code=start
/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    
    
    let commonStr = ''
    let minLen = Math.min(...strs.map(function(eleStr){
    
     
        return eleStr.length
    }))
    for(let i=0; i< minLen; i++){
    
    
        let s = []
        strs.forEach(ele=>{
    
    
            s.push(ele[i])
        })   
        if(s.every(item=>item==s[0])){
    
    
            commonStr += s[0]
        }else{
    
    
            break
        }
    }
    return commonStr
};
  1. valid brackets

Given a string s consisting only of '(', ')', '{', '}', '[', ']', determine whether the string is valid.
A valid string needs to satisfy:
the opening parenthesis must be closed with the same type of closing parenthesis.
Opening parentheses must be closed in the correct order.
Each closing parenthesis has a corresponding opening parenthesis of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false

Problem-solving idea:
Traverse the string, press and save it into the array when encountering a left parenthesis, and make a judgment when encountering a right parenthesis:
(1) Determine whether it is in right, and obtain the index of the right parenthesis in the right array
(2) Judgment Whether the last bit in the array is equal to left[index], pop if it is equal, otherwise it will not match, jump out of the loop,
and finally judge the result according to whether the flag and the length of the array are equal to 0

// @lc code=start
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    
    
    let left = ['(', '[', '{']
    let right = [')', ']', '}']
    let arr = []
    let flag = true
    for(let i=0; i<s.length; i++){
    
    
        //ES6新增的数组方法,用于检测数组是否包含某个元素,如果包含返回true,否则返回false,比较厉害的是,能直接检测NaN
        if(left.includes(s[i])) {
    
    
            arr.push(s[i])
            continue
        }
        let index = right.indexOf(s[i])
        if(index != -1) {
    
    
            if(arr[arr.length-1] == left[index]){
    
    
                arr.pop()
                continue
            }
            else{
    
    
                flag = false
                break
            }
        }
    }
    
    return flag && arr.length == 0

};

Guess you like

Origin blog.csdn.net/m0_43416592/article/details/130953628