leetcode, cattle off net javascript version (update)

  • Gives a 32-bit signed integer, you need this integer number on each inverted. (Assuming our environment obtained only store 32-bit signed integer, then the value range of [-231 231--1] Please Under this assumption, if the reverse it returns 0. integer overflow.)
var reverse = function(x) {
    const res=(Math.abs(x)+'').split('').reverse().join('')*(x>0?1:-1);
    return res<-Math.pow(2,31)||res>Math.pow(2,31)?0:res;
};
  • Determine whether an integer is a palindrome. Palindrome correct order (from left to right) and reverse (right to left) reading is the same integer.
var lengthOfLongestSubstring = function(s) {
    let result=[];
    let now=0;
    let arr=s.split('');
    arr.forEach((value,index)=>{
        let currentIndex=result.indexOf(value);
        result.push(value)
        result=result.slice(currentIndex+1);
        if(now<result.length){
            now=result.length;
        }
    })
    return now;
};
  • Given a string, you find out which does not contain a sub-length of the longest string of repeated characters.
    Example 1:

    Input: "abcabcbb"
    Output: 3
    Explanation: Because the longest substring of characters without repetition is "abc", so its length is 3.
    Example 2:

    Input: "bbbbb"
    Output: 1
    Explanation: Because the longest substring is repeated characters without "b", so that its length is 1.
    Example 3:

    Input: "pwwkew"
    Output: 3
    Explanation: Because the longest sub-string is repeated characters without "wke", so its length is 3.
    Please note that your answer must be a substring of length, "pwke" is a sub-sequence, not a substring.

var lengthOfLongestSubstring = function(s) {
    let result=[];
    let now=0;
    let arr=s.split('');
    arr.forEach((value,index)=>{
        let currentIndex=result.indexOf(value);
        result.push(value)
        result=result.slice(currentIndex+1);
        if(now<result.length){
            now=result.length;
        }
    })
    return now;
};
  • Given a non-negative integer nonempty array of integers represented, on the basis of the number plus one.

    Most significant digit stored in the first array, each element of the array stores a number only.

    You may assume that in addition to the integer 0, the integer does not begin with a zero.

    Example 1:

    Input: [1,2,3]
    Output: [2,4]
    Explanation: numeral 123 denotes the input array.
    Example 2:

    Input: [4,3,2,1]
    Output: [4,3,2,2]
    Explanation: input array represents a number 4321.

var plusOne = function (digits) {
    digits[digits.length-1] += 1;
    console.log(digits)
    var i = digits.length-1;
    while (true) {
      if (digits[i] >= 10) {
        digits[i] = 0;
        if (digits[i-1] === undefined) {
          //倒数第二位没有
          digits.unshift(1);
          break;
        } else {
          digits[i-1] += 1
        }
        i--
      }
      else {
        break;
      }
    }
    return digits
  }
  • 8 string conversion integer (atoi)
    invite you to implement a atoi function, it can convert a string to an integer.

    First, the function will begin with a space character discard useless if necessary, until the find to the first non-space character so far.

    When we find the first non-space character is a positive or negative number, the combination of the symbols as much as possible with consecutive numbers up later, as the sign of integer; if the first non-space character is figures, which directly after the continuous numeric characters are combined to form an integer.

    In addition to the string after a valid integer part may also exist extra characters, these characters can be ignored, they should not affect a function.

    Note: if the character string in the first non-space character is not a valid integer character string is empty or contains only white space character string, then you will not need to be a function of conversion.

    In any case, if the function can not effectively convert, 0 is returned.

var myAtoi = function(str) {
    return Math.max(Math.min(parseInt(str) || 0, 2147483647), -2147483648)
};

Given an array nums n comprises integers, determines whether there are three elements a, b, c nums such that a + b + c = 0? All the conditions are not satisfied to find duplicate triples.
Note: The answer can not contain duplicate triples.
For example, given the array nums = [-1, 0, 1 , 2, -1, -4],
meet the requirements of the set of triples as:
[
[-1, 0, 1],
[-1, -1, 2]
]

/*
  * 1、直接用三个 for 循环遍历所有数据,找出符合条件的数据,时间复杂度为 O(n^3)。能不能更快效率?
    2、先对数组内数据进行一次排序。O(nlogn)
    3、最外层一个 for 循环,先把其中一个值固定住(存放到变量),然后分别用两个指针指向数据的非固定值的头部和尾部,通过 while 循环来遍历。
    4、如果三个数据相加等于 0 了,就存储该三个值且更新 head 和 end 指针。
    5、如果不等于小于或大于 0 ,就更新 head 和 end 指针移动重新查找符合条件的值。
    6、返回结果集 result。
  * */
  var threeSum = function(nums) {
    let result=[];
    let head;
    let end;
    let fixedVal;
    nums.sort(function (a,b) {
      return a-b;
    })
    //判断数组内元素是否都为整数或负数,直接返回
    if(nums[0]>0||nums[nums.length-1]<0||nums.length<3){
      return result;
    }
    //遍历
    for(let i=0;i<nums.length;i++){
      fixedVal=nums[i];
      if(fixedVal === nums[i-1]) continue;
      //一开始的固定值为nums[0],所以头指针为 i+1 下一个元素
      head=i+1;
      //尾指针
      end=nums.length-1;
      //如果头指针小于尾指针
      while(head<end){
        if(nums[head]+nums[end]+fixedVal==0){
          let group=[];
          group.push(nums[head],nums[end],fixedVal);
          result.push(group);
          //存放完毕之后,不要忘记头指针和尾指针的移动(否则会产生死循环)
          head+=1;
          end-=1;
          //如果头指针满足小于尾指针且移动后的指针和移动前的指针元素相等,再往前移动
          while(head<end&&nums[head]==nums[head-1]){
            head+=1;
          }
          //如果头指针满足小于尾指针且移动后的指针和移动前的指针元素相等,再往后移动
          while(head<end&&nums[end]==nums[end+1]){
            end-=1;
          }
        }
        else if(nums[head]+nums[end]+fixedVal<0){
          head++;
        }
        else{
          end--
        }
      }
    }
    return result;
  }

Given a sorted array and a target, find the object in the array, and returns its index. If the target is not present in the array, it will be returned in sequence inserted position.
You may assume that no duplicate elements in the array.

var searchInsert = function(nums, target) {
    var index=nums.indexOf(target);
    var currentIndex;
    if(index!=-1){
      return index;
    }
    else{
      for(var i=0;i<nums.length;i++){
        if(target<=nums[i]){
          nums.splice(i,0,target);
          currentIndex=i;
          break;
        }
        else if(target>=nums[i]&&nums[i+1]>=target){
          console.log(nums[i],nums[i+1])
          nums.splice(i+1,0,target);
          currentIndex=i+1;
          break;
        }
        else if(target>=nums[nums.length-1]){
          nums.push(target);
          currentIndex=nums.length-1;
          break;
        }
      }
    }
    return currentIndex;
  };

Given a set of non-negative integers, their order rearranged so as to form a largest integer.
Example 1:

Input: [10,2]
Output: 210
Example 2:

Enter: [3,30,34,5,9]
output: 9,534,330
Description: The output can be quite large, so you need to return a string instead of an integer.

var largestNumber = function(nums) {
    nums.sort((a,b)=>{
        return parseInt(`${b}${a}`)-parseInt(`${a}${b}`)
    })
    return nums.join('').replace(/^[0]+/,'0')
};

The presence of repetitive elements
given an array of integers, determines whether there is a repeating element.

If no value appears at least twice in the array, the function returns true. If each element of the array is not the same, false is returned.

Example 1:

Input: [1,2,3,1]
Output: true
Example 2:

Input: [1,2,3,4]
Output: false
Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

var containsDuplicate = function(nums) {
    let arr=[...new Set(nums)];
    return arr.length!=nums.length
};

Array object to add a method to remove duplicates
Example 1

输入
[false, true, undefined, null, NaN, 0, 1, {}, {}, ‘a’, ‘a’, NaN]

Output
[false, true, undefined, null , NaN, 0, 1, {}, {}, 'a']

//方法1
Array.prototype.uniq = function () {
    var arr=[];
    var flag=true;
    for(var i=0;i<this.length;i++){
        if(arr.indexOf(this[i])==-1){
            if(this[i]!=this[i]){
                if(flag){
                    arr.push(this[i])
                    flag=false;
                }      
            }
            else{
                arr.push(this[i])
            }
        }
    }
    return arr;
}
//方法2
Array.prototype.uniq = function () {
	return [...new Set(this)];
}

Find two nodes closest to a common parent, may include node itself

function commonParentNode(oNode1, oNode2) {
    if(oNode1.contains(oNode2)){
        return oNode1;
    }
    else{
        return commonParentNode(oNode1.parentNode,oNode2)
    }
}

Input n integers, find the smallest number K. 4,5,1,6,2,7,3,8 e.g. eight digital inputs, the minimum number is four 1,2,3,4 ,.

function GetLeastNumbers_Solution(input, k)
{
    // write code here
    var result=input.sort(function(a,b){
        return a-b;
    })
    return result.length>=k?result.slice(0,k):[]
}

HZ occasionally get some professional issues to flicker those non-computer science students. After the test group will finish today, he spoke up: in the old one-dimensional pattern recognition, it is often necessary to calculate the maximum and continuous sub-vector when the vector is a positive whole number, the problem solved. However, if the vector contains a negative number, it should contain a negative number, and expect a positive number next to it would make up for it? For example: {6, -3, -2,7, -15,1,2,2}, and the maximum successive sub-vectors of 8 (beginning from 0, up to the third). To an array and returns its maximum continuous subsequence and you will not be fooled him live? (Sub-vector length is at least 1)

function FindGreatestSumOfSubArray(array){
    var max=array[0];
    var thum=array[0];
    for(var i=1;i<array.length;i++){
    	if(thum>0){
    		thum+=array[i]
    	}
    	else{
    		thum=array[i]
    	}
    	max=Math.max(thum,max)
    }
    return max
}

Guess you like

Origin blog.csdn.net/qq_33332184/article/details/90763356