This time I will bring you algorithms that are easy to encounter in JS interviews. The following is a practical case, let’s take a look.
Recommended related articles:The most complete collection of js interview questions in 2020 (latest)
Prime numbers
Q: How would you verify a prime number?
A: A prime number can only be divisible by itself and 1. So, I'm going to run a while loop and add 1. (Look at the code examples. If you can’t understand it, it’s not your cup of tea. Go back and learn the javaScript basics first and then come back.)
Method 1
function isPrime(n){ var pisor = 2; while (n > pisor){ if(n % pisor == 0){ return false; } else pisor++; } return true; } isPrime(137); // = true isPrime(237); // = false
Q: Can you do better?
A: Yes. The divisor increases by one at a time. After 3 I can add 2. If a number is divisible by any even number, it will be divisible by 2.
Supplement: If you don’t need to increase the divisor to this number. You can stop earlier. Let me explain it in the steps below (you can read it a few more times if you need to)
Step one, no number is divisible by a number greater than half of it. For example, 13 will never be divisible by 7,8,9...it can even be half of an even number. For example, 16 will be divisible by 8, but never by 9, 10, 11, 12...
Conclusion: A number will never be divisible by a number greater than half its value. So, we can loop 50% less.
Second step, now, if a number is not divisible by 3. (If it's divisible by 3, then it's not prime). Then, it is not divisible by any number greater than 1/3 of its value. For example, 35 is not divisible by 3. Therefore, it will never be divisible by a number greater than 35/3, never divisible by 12, 13, 14... If you take an even number like 36, it will never be divisible by 13, 14, 15.
Conclusion: A number is divisible by one-third of its value.
Step 3, for example, you have a number 127. 127 is not divisible by 2, so you should check at most 63.5. Secondly, 127 is not divisible by 3. So you will check to 127/3 approximately 42. It is not divisible by 5, the divisor should be less than 127/5 which is about 25, not 7. So, where do we stop?
Conclusion: The divisor will be less than math.sqrt(N)
Method 2
Don’t worry if you can’t understand it, just leave it alone. It doesn't matter if you're not a researcher.
function isPrime(n) { var pisor = 3, limit = Math.sqrt(n); //check simple cases if (n == 2 || n == 3) return true; if (n % 2 == 0) return false; while (pisor <p style="text-align: left;"><span style="color: #ff0000"><strong>Prime factors</strong></span></p><p style="text-align: left;">Q: How to find all the prime factors of a number? <br>A: Execute a while loop. Start dividing by 2. If it cannot be divided, record the divisor until completed. </p><pre class="brush:php;toolbar:false">function primeFactors(n){ var factors = [], pisor = 2; while(n>2){ if(n % pisor == 0){ factors.push(pisor); n= n/ pisor; } else{ pisor++; } } return factors; } primeFactors(69); // = [3, 23]
Q: What is the running time complexity? Can you do better?
A: O(n). You can start the divisor from 3 and add up to 2. Because, if a number is divisible by any even number, it will be divisible by 2. Therefore, you don't need to divide by even numbers. Furthermore, you won't have a factor larger than half its value. If you want to make it complicated, use the supplementary concepts from the first question.
Fibonacci (Fibonacci)
Q: How to get the nth Fibonacci number?
A: I create an array and start by iterating.
The Fibonacci series is one of the most popular interview questions for beginners. So, you have to learn this one.
Method 1
function fibonacci(n){ var fibo = [0, 1]; if (n <p style="text-align: left;">Q: What is the running time complexity? </p><p style="text-align: left;">A: O(n);</p><p style="text-align: left;">Q: Can you make it <a href="http://www.php.cn/wiki/80.html" target="_blank">recursive</a>? </p><p style="text-align: left;"><strong>Method 2</strong></p><pre class="brush:php;toolbar:false">function fibonacci(n){ if(n <p style="text-align: left;">Q: What is the running time complexity? <br>A: O(2n); Details about time complexity</p><p style="text-align: left;"><span style="color: #ff0000"><strong>Greatest common divisor</strong></span></p><p style="text-align: left;">Q: How would you find two What is the greatest common divisor of numbers? </p><pre class="brush:php;toolbar:false">function greatestCommonpisor(a, b){ var pisor = 2, greatestpisor = 1; //if u pass a -ve number this will not work. fix it dude!! if (a = pisor && b >= pisor){ if(a %pisor == 0 && b% pisor ==0){ greatestpisor = pisor; } pisor++; } return greatestpisor; } greatestCommonpisor(14, 21); // 7 greatestCommonpisor(69, 169); // = 1
Algorithm Paradigm
很抱歉。我也无法解释它。 因为我自己80%的情况下都不能理解它。 我的算法分析教练告诉我这个,又从课堂笔记偷走(我是一个好学生,顺便说一句!)
function greatestCommonpisor(a, b){ if(b == 0) return a; else return greatestCommonpisor(b, a%b); }
注意:用你的大脑来理解它。
去重
Q:你将如何从数组中删除重复的成员?
A: 执行一个循环,并保存一个对象/关联数组。如果我第一次找到一个元素,我会设置它的值为真(这将告诉我元素添加一次)。如果我在对象中找到这个元素,我不会将它插入到返回数组中。
function removeDuplicate(arr){ var exists ={}, outArr = [], elm; for(var i =0; i<arr.length removeduplicate><p style="text-align: left;"><span style="color: #ff0000"><strong>合并两个排序的数组</strong></span></p> <p style="text-align: left;">Q: 怎样合并两个已排序数组?<br>A: 我将为每个数组保留一个指针(看代码,并注意这个)。</p> <pre class="brush:php;toolbar:false">function mergeSortedArray(a, b){ var merged = [], aElm = a[0], bElm = b[0], i = 1, j = 1; if(a.length ==0) return b; if(b.length ==0) return a; /* if aElm or bElm exists we will insert to merged array (will go inside while loop) to insert: aElm exists and bElm doesn't exists or both exists and aElm <p style="text-align: left;">不通过临时<a href="http://www.php.cn/wiki/70.html" target="_blank">变量</a>交换两个数的值</p><p style="text-align: left;">Q:如何在不使用临时变量的情况下交换两个数字?</p><pre class="brush:php;toolbar:false">function swapNumb(a, b){ console.log('before swap: ','a: ', a, 'b: ', b); b = b -a; a = a+ b; b = a-b; console.log('after swap: ','a: ', a, 'b: ', b); } swapNumb(2, 3); // = before swap: a: 2 b: 3 // = after swap: a: 3 b: 2
位操作:对不起,我无法向你解释这一点。 Kinjal Dave建议到 logical conjunction理解它。将浪费您30分钟。
function swapNumb(a, b){ console.log("a: " + a + " and b: " + b); a = a ^ b; b = a ^ b; a = a ^ b; console.log("a: " + a + " and b: " + b); } swapNumb(2, 3); // = a: 2 and b: 3 // = a: 3 and b: 2
字符串反向
Q:如何在JavaScript中反转字符串?
A:可以遍历字符串并将字母连接到新字符串。
方法1
function reverse(str){ var rtnStr = ''; for(var i = str.length-1; i>=0;i--){ rtnStr +=str[i]; } return rtnStr; } reverse('you are a nice dude'); // = "edud ecin a era uoy"
Q:你知道在现代浏览器中串联效果很好,但在像IE8这样的旧浏览器中会变慢。 还有什么不同的方法,可以扭转一个字符串?
A:当然.我可以使用数组,也可以添加一些检查。如果字符串是NULL或其他字符串,这将失败。让我也做一些类型检查。使用此数组类似于在某些服务器端语言中使用字符串缓冲区。
方法2
function reverse(str){ var rtnStr = []; if(!str || typeof str != 'string' || str.length =0;i--){ rtnStr.push(str[i]); } return rtnStr.join(''); }
Q: 运行时间复杂度是多少?
A: O(n);
Q:可以做得更好?
A:我可以遍历索引的一半,它会节省一点点。 (这是没用的,可能不会打动面试官)
方法3
function reverse(str) { str = str.split(''); var len = str.length, halfIndex = Math.floor(len / 2) - 1, revStr; for (var i = 0; i <p style="text-align: left;">Q:这有效,但你可以做递归的方式吗?<br>A:可以。</p><p style="text-align: left;"><strong>方法4</strong></p><pre class="brush:php;toolbar:false">function reverse (str) { if (str === "") { return ""; } else { return reverse(str.substr(1)) + str.charAt(0); } }
方法5
Q:你可以在方法中使用任何构建,使它更清洁吗?
function reverse(str){ if(!str || str.length <p style="text-align: left;"><strong>方法6</strong></p><p style="text-align: left;">Q:你可以做反向函数作为字符串扩展吗?<br>A:我需要将这个函数添加到String.prototype,而不是使用str作为参数,我需要使用this</p><pre class="brush:php;toolbar:false">String.prototype.reverse = function (){ if(!this || this.length <p style="text-align: left;"><span style="color: #ff0000"><strong>单词反转</strong></span></p><p style="text-align: left;">Q:你如何在句子中颠倒单词?<br>A:您必须检查整个字符串的空白区域。确定是否可能有多个空格。</p><pre class="brush:php;toolbar:false">//have a tailing white space //fix this later //now i m sleepy function reverseWords(str){ var rev = [], wordLen = 0; for(var i = str.length-1; i>=0; i--){ if(str[i]==' ' || i==0){ rev.push(str.substr(i,wordLen+1)); wordLen = 0; } else wordLen++; } return rev.join(' '); }
内置方法的快速解决方案:
function reverseWords(str){ return str.split(' ').reverse(); }
原位反转
Q: 如果你有一个字符串如”I am the good boy”, 怎样变为 “I ma eht doog yob”? 注意这些单词位置不变但是被反转了。
A: 要做到这一点,我必须做字符串反向和字反转。
function reverseInPlace(str){ return str.split(' ').reverse().join(' ').split('').reverse().join(''); } reverseInPlace('I am the good boy');// = "I ma eht doog yob"
Q: ok。好的,你能不使用内置反向函数做到吗?
A: (内心独白)有没有搞错!!
//sum two methods. //you can simply split words by ' ' //and for each words, call reverse function //put reverse in a separate function //if u cant do this, //have a glass of water, and sleep
第一个非重复字符
Q: 怎么在字符串中找到第一个非重复字符?
A: 有什么条件吗?
A: 比如是否区分大小写?
面试官可能会说No。
A: 是长字符串还是短字符串?
Q: 这些有什么关系吗?
A:例如,如果它是一个非常长的字符串,说一百万个字符,我想检查是否有26个英文字符正在重复。 我可能会检查是否所有字符都在每200个字母中重复(例如),而不是循环遍历整个字符串。 这将节省计算时间。
Q: 简单起见, 这个字符串是 “the quick brown fox jumps then quickly blow air”。
function firstNonRepeatChar(str){ var len = str.length, char, charCount = {}; for(var i =0; i<len firstnonrepeatchar><p style="text-align: left;">这有一个问题,不能再循环中及时退出。</p> <p style="text-align: left;"><span style="color: #ff0000"><strong>删除重复的字符</strong></span></p> <p style="text-align: left;">Q: 怎样删除字符串中的重复字符?</p> <p style="text-align: left;">A: 这与第一个非重复字符非常相似。你应该问一些类似的问题。它是区分大小写的吗?。</p> <p style="text-align: left;">如果面试官说,这是区分大小写的,那么你就很轻松了。 如果他说不。你可以使用string.toLowercase()来把字符串。面试官可能不喜欢这个方法。 因为返回字符串不会拥有相同的大小写。 所以</p> <pre class="brush:php;toolbar:false">function removeDuplicateChar(str){ var len = str.length, char, charCount = {}, newStr = []; for(var i =0; i<len removeduplicatechar><p style="text-align: left;"><span style="color: #ff0000"><strong>回文检查</strong></span></p> <p style="text-align: left;">Q: 如何检查一个字符串是否是回文?</p> <p style="text-align: left;">A: 把字符串反转,如果反转前后相等,那么它就是回文。</p> <pre class="brush:php;toolbar:false">function isPalindrome(str){ var i, len = str.length; for(i =0; i<len ispalindrome><p style="text-align: left;">或者</p> <pre class="brush:php;toolbar:false">function checkPalindrom(str) { return str == str.split('').reverse().join(''); }
类似的:在 O(n)时间复杂度内判断一个字符串是否包含在回文字符串内。你能在O(1)时间解决问题吗?
找缺失的数字
Q: 在一个1到100的未排序数组中找到缺失的数,你怎么做?
说明:数组中的数字为1到100。 数组中只有一个数字缺失。数组未排序。找到缺少的数字。
A: 你必须表现得像是在想很多。然后讨论n=n(n+1)/2的线性级数之和
function missingNumber(arr){ var n = arr.length+1, sum = 0, expectedSum = n * (n+1)/2; for(var i = 0, len = arr.length; i <p style="text-align: left;">注意: 这个会返回任意长度数组中缺失的那个</p><p style="text-align: left;"><span style="color: #ff0000"><strong>两数之和</strong></span></p><p style="text-align: left;">Q: 在一个未排序的数组中找出是否有任意两数之和等于给定的数?<br>A: 简单!双重循环。</p><pre class="brush:php;toolbar:false">function sumFinder(arr, sum){ var len = arr.length; for(var i =0; i<len-1 sumfinder><p style="text-align: left;">Q: 时间复杂度?<br>A: O(n2)。<br>Q: 有更优解?<br>A: 我想想。我可以用一个对象来存储当前元素和和值的差值。当我拿到一个新元素,如果这个元素的差值在对象中存在,那么我就能判断出是否存在。</p> <pre class="brush:php;toolbar:false">function sumFinder(arr, sum){ var differ = {}, len = arr.length, substract; for(var i =0; i<len sumfinder><p style="text-align: left;"><span style="color: #ff0000"><strong>最大和</strong></span></p> <p style="text-align: left;">Q: 找到任意两个元素的最大总和?</p> <p style="text-align: left;">A: 这实际上非常简单直接。 找到两个最大的数字并返回它们的总和</p> <pre class="brush:php;toolbar:false">function topSum(arr){ var biggest = arr[0], second = arr[1], len = arr.length, i = 2; if (len biggest){ second = biggest; biggest = arr[i]; } else if (arr[i]>second){ second = arr[i]; } } return biggest + second; }
统计零
Q: 统计从1到n的零总数?
A: 如果 n = 100,则0的数目将是11(0,10,20,30,40,50,60,70,80,90,100)。 请注意,100有两个0.这个看起来很简单,但有点棘手
说明:所以这里的重点是。 如果你有一个1到50的数字,那么这个数值就是5,就是50除以10.然而,如果这个数值是100,这个数值是11,你将得到100/10 = 10和 10/10 = 1。 那就是你将如何在一个数字中得到更多的零,如(100,200,1000);
function countZero(n){ var count = 0; while(n>0){ count += Math.floor(n/10); n = n/10; } return count; } countZero(2014); // = 223
子字符串
Q: 在字符串中匹配子字符串?
A: 在迭代字符串时将使用指针(一个用于字符串,另一个用于子字符串)。 然后用另一个变量来保存初始匹配的起始索引。
function subStringFinder(str, subStr){ var idx = 0, i = 0, j = 0, len = str.length, subLen = subStr.length; for(; i<len substringfinder><p style="text-align: left;"><span style="color: #ff0000"><strong>排列</strong></span></p> <p style="text-align: left;">Q: 如何获取字符串中的所有排列?</p> <p style="text-align: left;">A: 根据您对算法的了解程度,这可能会很困难。、</p> <pre class="brush:php;toolbar:false">function permutations(str){ var arr = str.split(''), len = arr.length, perms = [], rest, picked, restPerms, next; if (len == 0) return [str]; for (var i=0; i<len><p>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!</p> <blockquote><p>相关学习推荐:<a href="https://www.php.cn/course/list/17/type/2.html" target="_blank">javascript视频教程</a></p></blockquote></len>
The above is the detailed content of Algorithms that are easy to encounter in JS interviews. For more information, please follow other related articles on the PHP Chinese website!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.