摘要:這是我在平時(shí)有時(shí)間的時(shí)候做的一些算法上的題目想看更新請(qǐng)移步這里題目描述解法這個(gè)問(wèn)題當(dāng)時(shí)拿到的時(shí)候是完全沒(méi)有思路的,后面上網(wǎng)查詢(xún)了一下這個(gè)題目,知道了使用斐波那契數(shù)列就能夠解這道題目,,,當(dāng)然百度作業(yè)幫上面也有相應(yīng)的解法,套路就是題目為一
這是我在平時(shí)有時(shí)間的時(shí)候做的一些算法上的題目
想看更新請(qǐng)移步這里
題目: Climbing Stairs 描述You are climbing a stair case.It takes n steps to reach to the top Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer.解法
這個(gè)問(wèn)題當(dāng)時(shí)拿到的時(shí)候是完全沒(méi)有思路的,后面上網(wǎng)查詢(xún)了一下這個(gè)題目,知道了使用
斐波那契數(shù)列就能夠解這道題目,`F(0)=1,F(xiàn)(1)=1, F(n)=F(n-1)+F(n-2)(n>=2
,n∈N*)`當(dāng)然百度作業(yè)幫上面也有相應(yīng)的解法,套路就是
題目為一次可以走一步或兩步: a[1]=1;a[2]=2; 假設(shè)i的范圍為3~n(n 為樓梯數(shù)),關(guān)系式為: a[i]=a[i-1]+a[i-2]; 若題目為一次可以走一步或兩步或三步: a[1]=1;a[2]=2;a[3]=4; 假設(shè)i的范圍為4~n(n為樓梯數(shù)),關(guān)系式為: a[i]=a[i-1]+a[i-2]+a[i-3];
但是當(dāng)初看到這個(gè)數(shù)列的公式,第一想法是使用遞歸,然后,由于堆棧溢出,失敗了
再看看后面的百度作業(yè)幫的那個(gè)公式,再聯(lián)想一下數(shù)列,于是想到了使用數(shù)列這樣的
結(jié)構(gòu)來(lái)解決
/** * @param {number} n * @return {number} */ var climbStairs = function(n) { if (isNaN(n)) return -1; if (n<=0) return -1; if (n<=2) return n; if (n>=3) { var res = [1,2]; for(var i=2;i題目: Find the odd int 描述 Given an array, find the int that appears an odd number of times. There will always be only one integer that appears an odd number of times.解法這是我的解法,寫(xiě)的真的很丑,勿噴哦
function findOdd(A) { //happy coding! let indecies = []; A.forEach(a => { let idx = A.indexOf(a); let index = []; while (idx !== -1) { index.push(idx); idx = A.indexOf(a, idx + 1); } indecies.push(index); }); const a = indecies.filter(index => (index.length % 2 !== 0)); return A[a[0][0]]; }然后是大神的解法,使用的是位運(yùn)算(說(shuō)實(shí)話(huà),還不是很懂位運(yùn)算,如果有什么見(jiàn)解,歡迎留言)
function findOdd(A) { //happy coding! return A.reduce((a, b) => a^b); }題目:You"re a square! 描述Given an integral number, determine if it"s a square number: isSquare(-1) => false isSquare( 3) => false isSquare( 4) => true isSquare(25) => true isSquare(26) => false解法這道就簡(jiǎn)單了
var isSquare = function(n){ return Number.isInteger(Math.sqrt(n)); }題目:Strings to numbers 描述You are given an array of numbers in string form. Your task is to convert this to an array of numbers. Your function can only be a maximum of 30 characters long (not including whitespaces)! I have limited the char count because there is a very short and easy way to achieve this task. Here is an example of what your function needs to return: ["1","2","3"] => [1,2,3] Edge Cases: 1 - If your function comes up against a value that isn"t a number its place in the array must be substituted with NaN. 2 - An empty array must return an empty array.解法這道題主要是有一個(gè)代碼字?jǐn)?shù)限制,只能在30個(gè)字符以?xún)?nèi),使用了ES6的箭頭函數(shù)
var convert = a => a.map(n => n*1)題目:Thinkful - List and Loop Drills: Inverse Slicer 描述You"re familiar with list slicing in Python and know, for example, that: >>> ages = [12, 14, 63, 72, 55, 24] >>> ages[2:4] [63, 72] >>> ages[2:] [63, 72, 55, 24] >>> ages[:3] [12, 14, 63] write a function inverse_slice() that takes three arguments: a list items, an integer a and an integer b. The function should return a new list with the slice specified by items[a:b] excluded For example: >>>inverse_slice([12, 14, 63, 72, 55, 24], 2, 4) [12, 14, 55, 24] The input will always be a valid list, a and b will always be different integers equal to or greater than zero, but they may be zero or be larger than the length of the list.解法這道題也相對(duì)簡(jiǎn)單
function inverseSlice(items, a, b) { return items.filter((item, index) => !((index >= a) && (index < b))); }題目:Get all array elements except those with specified indexes 描述Extend the array object with a function to return all elements of that array, except the ones with the indexes passed in the parameter. For example: var array = ["a", "b", "c", "d", "e"]; var array2 = array.except([1,3]); // array2 should contain ["a", "c", "e"]; The function should accept both array as parameter but also a single integer, like this: var array = ["a", "b", "c", "d", "e"]; var array2 = array.except(1); // array2 should contain ["a", "c", "d", "e"];解法我的解法
Array.prototype.except = function(keys) { if (typeof keys === "number") { return this.filter((item, index) => index !== keys); } if (Array.isArray(keys)) { return this.filter((item, index) => !keys.includes(index)); } return -1; }大神的解法
Array.prototype.except = function(keys) { if(!Array.isArray(keys)) keys = [keys]; return this.filter((a,i) => !keys.includes(i)); }題目:Sum of a Sequence [Hard-Core Version] 描述The task is simple to explain: simply sum all the numbers from the first parameter being the beginning to the second parameter being the upper limit (possibly included), going in steps expressed by the third parameter: sequenceSum(2,2,2) === 2 sequenceSum(2,6,2) === 12 // 2 + 4 + 6 sequenceSum(1,5,1) === 15 // 1 + 2 + 3 + 4 + 5 sequenceSum(1,5,3) === 5 // 1 + 4 If it is an impossible sequence (with the beginning being larger the end and a positive step or the other way around), just return 0. See the provided test cases for further examples :) Note: differing from the other base kata, much larger ranges are going to be tested, so you should hope to get your algo optimized and to avoid brute-forcing your way through the solution.解法這道題有點(diǎn)意思,細(xì)心的人就會(huì)發(fā)現(xiàn)給出的例子里面可以看出一些等差數(shù)列的影子,那么我們
就可以按照等差數(shù)列的方法來(lái)解這道題了,等差數(shù)列求和公式:(首項(xiàng) + 末項(xiàng))* 項(xiàng)數(shù) / 2function sequenceSum(begin, end, step){ //your code here const n = Math.floor((end - begin) / step) + 1; if (n<0) return 0; const An = begin + ((n-1) * step); return n * (begin + An) / 2; }注意:這里面我們需要求項(xiàng)數(shù)N和末項(xiàng)An,至于N怎么求的,那就要靠自己去發(fā)現(xiàn)規(guī)律
題目:Array.prototype.size() 描述Implement Array.prototype.size() - without .length ! Implement Array.prototype.size(), which should simply return the length of the array. But do it entirely without using Array.prototype.length! Where .length is a property, .size() is a method. Rules Because it is quite impossible to disable [].length, and because filtering for "length" is an iffy proposition at best, THIS KATA WORKS ON THE HONOUR SYSTEM. You may cheat. But you may have trouble sleeping. Or $DEITY may kill a puppy. You need not support sparse arrays (but you may!). All testing will be done with dense arrays. Values will not be undefined. You need only support actual, real arrays. Your method needs to be read only. Arguments must be ignored. The this object must not be modified.解法我的解法
Array.prototype.size = function () { var i = 0; while (this[i] !== undefined) i++; return i; };大神的解法
Array.prototype.size = function() { return this.reduce(r => r + 1, 0); };在這里看了下大神的解法,讓我對(duì)reduce函數(shù)又有了新的理解
題目:Find the smallest integer in the array 描述Find the smallest integer in the array. Given an array of integers your solution should find the smallest integer. For example: Given [34, 15, 88, 2] your solution will return 2 Given [34, -345, -1, 100] your solution will return -345 You can assume, for the purpose of this kata, that the supplied array will not be empty.解法我的解法
function findSmallestInt(args) { return args.sort((a, b) => { return a - b; })[0]; }大神的解法
function findSmallestInt(args) { return Math.min(...args); }題目:Replace With Alphabet Position 描述Welcome. In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn"t a letter, ignore it and don"t return it. a being 1, b being 2, etc. As an example: alphabet_position("The sunset sets at twelve o" clock.") Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (As a string.)解法我的解法
function alphabetPosition(text) { let alphabet = {}; let arr = []; const lowCaseText = text.toLowerCase(); for (let i = 0; i < 26; i++) { alphabet[(String.fromCharCode((65+i))).toLowerCase()] = (i + 1); } for (let j = 0; j < text.length; j++) { if (alphabet[lowCaseText[j]]) { arr.push(alphabet[lowCaseText[j]]); } } return arr.join(" "); }大神的解法
function alphabetPosition(text) { var result = ""; for (var i = 0; i < text.length; i++){ var code = text.toUpperCase().charCodeAt(i) if (code > 64 && code < 91) result += (code - 64) + " "; } return result.slice(0, result.length-1); }題目:GetSum 描述Given two integers, which can be positive and negative, find the sum of all the numbers between including them too and return it. If both numbers are equal return a or b. Note! a and b are not ordered! Example: GetSum(1, 0) == 1 // 1 + 0 = 1 GetSum(1, 2) == 3 // 1 + 2 = 3 GetSum(0, 1) == 1 // 0 + 1 = 1 GetSum(1, 1) == 1 // 1 Since both are same GetSum(-1, 0) == -1 // -1 + 0 = -1 GetSum(-1, 2) == 2 // -1 + 0 + 1 + 2 = 2解法依然是等差數(shù)列
function GetSum( a,b ) { //Good luck! return (a + b) * (Math.abs(b - a) + 1) / 2; }題目:Add Two Numbers 描述You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8解法javascript linked list structure
linked list 是一種鏈表結(jié)構(gòu),用于存儲(chǔ)數(shù)字類(lèi)似于:
// 807這個(gè)數(shù)字的存儲(chǔ)結(jié)構(gòu) var num8 = { val: 8, next: null, } var num0 = { val: 0, next: num8, } var num7 = { val: 7, next: num0, } // 807這個(gè)數(shù)字就能夠用這樣的結(jié)構(gòu)得到就只是用一個(gè)新的linked list來(lái)儲(chǔ)存相加後的結(jié)果
要注意的就是list1跟list2長(zhǎng)度可能不一樣
另外就是相加後可能比9還大,需要考慮進(jìn)位的情況/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function(l1, l2) { var list = new ListNode(0); //儲(chǔ)存輸出的結(jié)果,因?yàn)閘ist的指針要不斷往後移,因此用一個(gè)假節(jié)點(diǎn)方便操作 var result = list; // 使用一個(gè)ListNode來(lái)儲(chǔ)存相加的結(jié)果 var sum,carry = 0; // carry用來(lái)處理進(jìn)位 //當(dāng) list1, list2 都沒(méi)有值,而且carry也為0的時(shí)候才結(jié)束迴圈 while(l1 || l2 || carry > 0){ sum = 0; // list1與list2長(zhǎng)度可能不同,分開(kāi)處理 if(l1!== null){ sum += l1.val; l1 = l1.next; } if(l2!==null){ sum += l2.val; l2 = l2.next; } // 如果之前有進(jìn)位,carry = 1;沒(méi)有的話(huà)carry = 0 sum += carry; list.next = new ListNode(sum%10); //相加如果超過(guò)9,只能留下個(gè)位數(shù)放入結(jié)果list,十位數(shù)的地方進(jìn)位 carry = parseInt(sum/10); // list指標(biāo)向後 list = list.next; } // 因?yàn)榈谝粋€(gè)節(jié)點(diǎn)為假節(jié)點(diǎn),跳過(guò) return result.next; }// The complete code for the List constructor is: function List() { List.makeNode = function() { return {data: null, next: null}; }; this.start = null; this.end = null; this.add = function(data) { if (this.start === null) { this.start = List.makeNode(); this.end = this.start; } else { t this.end.next = List.makeNode(); this.end = this.end.next; } ; this.end.data = data; }; this.delete = function(data) { var current = this.start; var previous = this.start; while (current !== null) { if (data === current.data) { if (current === this.start) { this.start = current.next; return; } if (current === this.end) this.end = previous; previous.next = current.next; return; } previous = current; current = current.next; } }; this.insertAsFirst = function(d) { var temp = List.makeNode(); temp.next = this.start; this.start = temp; temp.data = d; }; this.insertAfter = function(t, d) { var current = this.start; while (current !== null) { if (current.data === t) { var temp = List.makeNode(); temp.data = d; temp.next = current.next; if (current === this.end) this.end = temp; current.next = temp; return; } current = current.next; } }; this.item = function(i) { var current = this.start; while (current !== null) { i--; if (i === 0) return current; current = current.next; } return null; }; this.each = function(f) { var current = this.start; while (current !== null) { f(current); current = current.next; } }; }題目:Reverse String 描述Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh".解法我的解法
"hello" -> ["h","e","l","l","o"] -> "o"+"l"+"l"+"e"+"h"
var reverseString = function(s) { var result = ""; var ary = s.split(""); for(var i = ary.length-1 ; i >= 0 ; i--){ result = result + ary[i]; } return result; };進(jìn)階解法
未交換前 ["h","e","l","l","o"]
第1次交換 ["h","e","l","l","o"] o,h互換 ["o","e","l","l","h"]第2次交換 ["o","e","l","l","h"] e,l互換 ["o","l","l","e","h"]
var reverseString = function(s) { var result = ""; var ary = s.split(""); for(var i = 0, max = (ary.length-1)/2 ; i < max ; i++){ var temp = ary[i]; ary[i] = ary[ary.length - 1 - i]; ary[ary.length - 1 - i] = temp; } return ary.join(""); };題目:Valid Anagram 描述Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. Note: You may assume the string contains only lowercase alphabets. Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?解法我的解法
要比較兩個(gè)字串裡面的字元是否相同,首先可以判斷長(zhǎng)度是否相等,不相等就可以直接判定
為false 接下來(lái)將重新排序後的字串比較是否相等。
/** * @param {string} s * @param {string} t * @return {boolean} */ var isAnagram = function(s, t) { if(s.length !== t.length) return false; var s1 = s.split("").sort().join(""); var t1 = t.split("").sort().join(""); return s1 === t1; };
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/81335.html
摘要:一個(gè)寫(xiě)著玩的客戶(hù)端,代碼不復(fù)雜,輕松了解比特幣。項(xiàng)目地址起因看書(shū)確實(shí)是很好的學(xué)習(xí)比特幣的方法,但是沒(méi)有代碼的幫助,理解比特幣如何實(shí)現(xiàn)時(shí),很是困難。后來(lái)發(fā)現(xiàn)一個(gè)用寫(xiě)的完整客戶(hù)端,就決定用它來(lái)研究比特幣源碼了,幫助我理解比特幣。 一個(gè)寫(xiě)著玩的 bitcoin 客戶(hù)端,代碼不復(fù)雜,輕松了解比特幣。項(xiàng)目地址:https://github.com/jiangleo/b... 起因 看書(shū)確實(shí)是很好...
摘要:一個(gè)寫(xiě)著玩的客戶(hù)端,代碼不復(fù)雜,輕松了解比特幣。項(xiàng)目地址起因看書(shū)確實(shí)是很好的學(xué)習(xí)比特幣的方法,但是沒(méi)有代碼的幫助,理解比特幣如何實(shí)現(xiàn)時(shí),很是困難。后來(lái)發(fā)現(xiàn)一個(gè)用寫(xiě)的完整客戶(hù)端,就決定用它來(lái)研究比特幣源碼了,幫助我理解比特幣。 一個(gè)寫(xiě)著玩的 bitcoin 客戶(hù)端,代碼不復(fù)雜,輕松了解比特幣。項(xiàng)目地址:https://github.com/jiangleo/b... 起因 看書(shū)確實(shí)是很好...
摘要:所以我們還是以的角度去看待一個(gè)項(xiàng)目。在中最耀眼的當(dāng)屬了,作為一個(gè)貫穿整個(gè)項(xiàng)目的框架,為項(xiàng)目開(kāi)發(fā)帶來(lái)依賴(lài)注入,面向切面編程的功能。說(shuō)到這里,其實(shí)一個(gè)簡(jiǎn)單的完整的項(xiàng)目就差不多了。 showImg(https://segmentfault.com/img/remote/1460000016219391); 前言 最近自己做了幾個(gè)Java Web項(xiàng)目,有公司的商業(yè)項(xiàng)目,也有個(gè)人做著玩的小項(xiàng)目,...
摘要:所以我們還是以的角度去看待一個(gè)項(xiàng)目。在中最耀眼的當(dāng)屬了,作為一個(gè)貫穿整個(gè)項(xiàng)目的框架,為項(xiàng)目開(kāi)發(fā)帶來(lái)依賴(lài)注入,面向切面編程的功能。說(shuō)到這里,其實(shí)一個(gè)簡(jiǎn)單的完整的項(xiàng)目就差不多了。 showImg(https://segmentfault.com/img/remote/1460000016219391); 前言 最近自己做了幾個(gè)Java Web項(xiàng)目,有公司的商業(yè)項(xiàng)目,也有個(gè)人做著玩的小項(xiàng)目,...
閱讀 856·2023-04-25 21:21
閱讀 3237·2021-11-24 09:39
閱讀 3079·2021-09-02 15:41
閱讀 2009·2021-08-26 14:13
閱讀 1839·2019-08-30 11:18
閱讀 2786·2019-08-29 16:25
閱讀 517·2019-08-28 18:27
閱讀 1590·2019-08-28 18:17