Digression

It's been a while codewars Of JavaScript After the title , It gives me the biggest feeling is , It will help you quickly improve the language you want to practice API Degree of familiarity ,Array object 、String Objects and other native methods , Constructors 、 Some algorithm problems, etc . Every time submit after , Look at your own code , Take a look at the code written by others . I found that the code I wrote and the implementation ideas were just weak and explosive . therefore , Every time it's in submi After that , I'll see Top five The answer , Understand Daniu's solution ( Most of the time , The code will use ES6 The grammar of , Very concise ), then train again. In this way , Practice for nearly 20 Next day's time . This is my in codewars The results of the above ,5kyu, It's painted 93 topic , There are some topics I can't think of , Just unlock solutions 了 . therefore Honor Completed Kata Not at all 100%.

I started playing recently leetcode 了 , Change plaform Mainly because leetcode Most of the questions on the Internet are interview questions of major Internet companies , And most of them are algorithms . It happens that I am eager to improve my ability in this field recently . So it shifted plaform, Although I'm a little reluctant :"( . But I will continue to play codewars Of /

1-20 leetcode Personal problem solving ideas



Realize the idea : Create an empty array , Write two loops . The variable initialization of the second loop is based on the first loop . Then make a judgment , If nums[i] + nums[j] === target, Just exit the loop .

// Old ideas , Due to the proposal of netizens , The time complexity of the algorithm is O(n^2)
var twoSum = function(nums, target) {
let index = [];
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
index.push(i);
index.push(j);
break;
}
}
}
return index;
};
// New ideas :
var twoSum = function(nums, target) {
let arr = [],
obj = {},
len = nums.length;
for (let i = 0; i < len; i++) {
if (obj[target - nums[i]] !== undefined) {
arr[0] = obj[target - nums[i]];
arr[1] = i;
return arr;
}
obj[nums[i]] = i;
}
};

ZigZag Conversion(Difficulty: Easy; Tags: String)



First , In order to complete this topic , What we need to understand is .ZigZag pattern What does it have to do with a given number of rows .

It's simple , Only 2 That's ok 、3 That's ok 、4 Line time zigzag Their shapes are as follows



The main idea of this topic is to understand the given Row number And the position of the letters to be extracted in each line .

  1. When there is only one line , Return the original string directly
  2. When it's larger than one line , The first and last lines have the same pattern , namely ( Suppose the specified number of rows is n, here n>1) Every circle ( Code a value ) Every time [ n - (n - 2) ] * (n - 1) Once in a position
  3. Except for the first and last lines , There is also a regular distribution of the number of circles in the middle : The last value of the blue arrow is different from the previous value 2 * (n - 1) A place , The two values of the green arrow also follow this rule . therefore , The implementation code is as follows

var convert = function(s, numRows) {
if (numRows === 1) return s;
let str = '';
let num = (numRows - (numRows - 2)) * (numRows - 1); //2
for (let i = 1; i <= numRows; i++) {
for (let j = i - 1; j < s.length; j += num) {
if (i === 1 || i === numRows) {
str += s.slice(j, j + 1);
} else {
str += s.slice(j, j + 1);
str += s.slice(j + num - (2 * (i - 1)), j + num - (2 * (i - 1)) + 1);
}
}
}
return str;
};
console.log(convert("123456789", 2)); //135792468
console.log(convert("123456789", 3)); //159246837
console.log(convert("123456789", 4)); //172683594
console.log(convert("1234567891234567891234", 5)); //1982817937261463524543



This topic is very interesting , The topic is very direct , Let's go input Finger of reverse. But there are demands , Is that when reverse If the value of exceeds 32bit, We're going back to 0.

The idea is to use JS Or operation of |, The immediate operator , take reverse The value of is converted to 32 position , Then compare it with the original value .

Math.pow(2, 32)|0 return 0 (Math.pow(2, 32) + 1)|0 return 1. So the logic of solving the problem is

var reverse = function(x) {
let str1 = x.toString().match(/[0-9]/g).reverse().join('');
let str2 = x.toString().match(/[^0-9]/g) === null ? '' : x.toString().match( /[^0-9]/g).join('');
let num1 = Number(str2 + str1)|0; //reverse and transform to 32bit
let num2 = Number(str2 + str1);
return num1 === num2 ? num2 : 0;
};

This topic , This paper focuses on the data types NaN Understanding and understanding of methods isNaN() The understanding of the , At the same time, we will examine the influence of Number、parseInt、parseFloat Differences in methods . Here's a simple statement .

NaN

NaN, Non numerical value (Not a Number) It's a special number , This value is used to represent an operand that is supposed to return a value

If no value is returned ( So that no errors are thrown ). Any number divided by 0 Returns the NaN.

NaN Not equal to any value , Include NaN In itself . therefore console.log(NaN === NaN) // false

isNaN It is used to determine whether the parameter is “ Not numerical ”.

parseInt

parseInt and parseFloat Used to convert a string to a numeric type , and Number Used to convert any data type , Here is a brief introduction parseInt.

parseInt The space before the string is ignored , Until a non space character is found . If the first character is not a numeric character or a minus or plus sign ,parseInt Returns the NaN. in other words , use parseInt() Converting an empty string returns NaN(Number() Returns... For null characters 0) If the first character is a numeric character ,parseInt() Will continue to parse the second character , Until all subsequent characters are parsed or a non numeric character is encountered . for example ,"1234blue" Will be converted to 1234, because "blue" Will be completely ignored . Similarly ,"22.5" Will be converted to 22, Because the decimal point is not a valid numeric character ;'-123' Will be converted to -123, Because the first character is a minus sign , And the following characters are numbers ;'-+123' Returns the NaN, Because the first character is -, And the second character is +, Not in line with the normal numerical model .

therefore , The solution to this problem is as follows :

var myAtoi = function(str) {
let symbol = '';
str = str.replace(/^\s+|\s+$/g, '');// Remove the spaces at both ends
str = isNaN(parseInt(str)) ? 0 : parseInt(str);
if (str > Math.pow(2, 31) - 1) {
return Math.pow(2, 31) - 1;
} else if (str < - Math.pow(2, 31)) {
return - Math.pow(2, 31);
} else {
return str;
}
};

Ongoing update ...

leetcode Algorithm problem (JavaScript Realization ) More articles about

  1. LeetCode Algorithm problem -Subdomain Visit Count(Java Realization )

    This is the number one of Yuele book 320 Secondary update , The first 341 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 189 topic ( Sequence question no 811). image "discuss.leetcode.com& ...

  2. LeetCode Algorithm problem -Number of Lines To Write String(Java Realization )

    This is the number one of Yuele book 319 Secondary update , The first 340 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 188 topic ( Sequence question no 806). We're going to give the string S The letters are written in lines from left to right . The maximum width of each line is ...

  3. LeetCode Algorithm problem -Unique Morse Code Words(Java Realization )

    This is the number one of Yuele book 318 Secondary update , The first 339 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 186 topic ( Sequence question no 804). The International Morse code defines a standard code , Each of these letters maps to a series of ...

  4. LeetCode Algorithm problem -Rotate String(Java Realization )

    This is the number one of Yuele book 317 Secondary update , The first 338 Original article Before starting today's algorithm problem , Say a few words , Today is world reading day , Recommend two books to you ,< Lifelong growth > and < Zen and motorcycle maintenance Art >, It's worth reading and rereading . 0 ...

  5. LeetCode Algorithm problem -Rotated Digits(Java Realization )

    This is the number one of Yuele book 316 Secondary update , The first 337 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 185 topic ( Sequence question no 788). If a number goes through 180 After degree rotation , It's a different number ...

  6. LeetCode Algorithm problem -Letter Case Permutation(Java Realization )

    This is the number one of Yuele book 315 Secondary update , The first 336 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 184 topic ( Sequence question no 784). Given a string S, Convert each letter individually to lowercase or uppercase to create another ...

  7. LeetCode Algorithm problem -Minimum Distance Between BST Nodes(Java Realization - Four solutions )

    This is the number one of Yuele book 314 Secondary update , The first 335 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 183 topic ( Sequence question no 783). Given a binary search tree with root values (BST), Returns any two objects in the tree ...

  8. LeetCode Algorithm problem -Jewels and Stones(Java Realization )

    This is the number one of Yuele book 313 Secondary update , The first 334 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 182 topic ( Sequence question no 771). character string J Representative jewelry ,S Represents the stone you have .S Every character in is ...

  9. LeetCode Algorithm problem -Toeplitz Matrix(Java Realization )

    This is the number one of Yuele book 312 Secondary update , The first 333 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 181 topic ( Sequence question no 766). If every diagonal from the top left to the bottom right has the same element , Then the matrix is ...

  10. LeetCode Algorithm problem -Prime Number of Set Bits in Binary Representation(Java Realization )

    This is the number one of Yuele book 311 Secondary update , The first 332 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 180 topic ( Sequence question no 762). Given two positive integers L and R, stay [L,R] Within the scope of , Calculate the number of each integer ...

Random recommendation

  1. JQuery Choose Radio

    <tr> <td> <input type="radio" name="rdb" value=" Enable " che ...

  2. poj 1985 Cow Marathon

    Topic linking http://poj.org/problem?id=1985 Cow Marathon Description After hearing about the epidemic of obe ...

  3. AjaxFileUpload Firefox It doesn't work (zero-width space characters from a JavaScript string)

    Firefox The returned prompt reports an error parse error (Chrome and IE normal ) Print out the returned string , Visual inspection is normal Put the string in notepad++, Convert the character set to ANSI It's found that there are more Euro symbols adopt j ...

  4. (Stack)Basic Calculator I &amp;&amp; II

    Basic Calculator I Implement a basic calculator to evaluate a simple expression string. The expressi ...

  5. Java Language

    Java Programming language is a simple . Completely object-oriented . Distributed . Explanatory . robust . Security has nothing to do with the system . portable . High performance . Multithreading and dynamic programming languages . Java Can write cross platform applications , Yes, there is Sun Microsystems The company 199 ...

  6. Python Character encoding of

    Python Character encoding of 1. Python Introduction to character encoding 1. 1  ASCII Python The interpreter is loading .py File code , The content will be encoded , The general default is ASCII code .ASCII(American St ...

  7. socket, Simulate server 、 Client communication

    Server code : using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;u ...

  8. js Realization json Array set de duplication , Difference set , Combine , intersection .

    let list = [ { id: "1", content: "A" }, { id: "2", content: "B&qu ...

  9. 2018 CCPC Online games hdu6444 Neko&#39;s loop

    Title Description : Neko has a loop of size n.The loop has a happy value ai on the i−th(0≤i≤n−1) grid. Neko likes ...

  10. Linux The basic order of

    -shutdown –h now(root It's the users that make it work )     Shutdown immediately -shutdown –r now(root It's the users that make it work )     Restart your computer now -reboot               ...