search
HomeWeb Front-endJS TutorialWhat are the basic algorithms of Js?

What are the basic algorithms of Js?

May 02, 2018 am 09:46 AM
javascriptWhichalgorithm

This time I will bring you what are the basic algorithms of Js and what are the precautions when using the basic algorithms of Js. The following is a practical case, let's take a look.

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

Algorithmic Paradigm

Sorry. I can't explain it either. Because I myself can't understand it 80% of the time. My algorithm analysis instructor told me this, and stole it from class notes (I was a good student, btw!)

function greatestCommonpisor(a, b){
 if(b == 0)
  return a;
 else 
  return greatestCommonpisor(b, a%b);
}

NOTE: Use your brain to understand it.

Deduplication

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>
<p>推荐阅读:</p>
<p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-394797.html" target="_blank">你微信小程序登录鉴权使用技巧</a><br></p>
<p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-394795.html" target="_blank">webpack模块热替换使用详解</a><br></p></len>

The above is the detailed content of What are the basic algorithms of Js?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

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),

MantisBT

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.