23: Minimum number of K
Title Description
Enter n integers to find the smallest number of K. For example, enter 4,5,1,6,2,7,3,8 these 8 numbers, then the smallest 4 number is 1,2,3,4,.
Simple question ....
function GetLeastNumbers_Solution(input, k){ if(k>input.length) return []; let ans = []; input = input.sort(); //console.log(input.join("").slice(0,4).split("")); input.join("").slice(0,k).split("").map(function(item,index) { ans.push(parseInt(item)) }); return ans; }
24: Maximum and large contiguous sub-arrays
Title Description
Hertz occasionally takes some professional questions to confuse students who are not computer majors. Today, the test team after the meeting, he said again: in the Ancient one-dimensional pattern recognition, it is often necessary to calculate the maximum sum of continuous sub-vectors, when the vector is all positive, the problem is well solved. However, if the vector contains a negative number, should it contain a negative number and expect that the next positive number will compensate for it? For example: {6,-3,-2,7,-15,1,2,2}, the maximum and 8 of continuous sub-vectors (starting from No. 0 to 3rd). Will you be fooled by him? (The length of the sub-vector is at least 1)
DP entry, which was done a few years ago (plus record location): 51569801
function FindGreatestSumOfSubArray(array){ let len = array.length; let max = -Infinity; let tmp = 0; let sum = 0; for(let i = 0; i < len; i++) { sum+=array[i]; if(sum>max) { max = sum; } if(sum<0) { sum = 0; } } return max;}
25: Entry node of the ring in the linked list
Turtle and Rabbit Race method:
The first step is to find the loop in the meeting point. Using P1,P2 to point to the list head, p1 each step, p2 each walk two steps, until P1==P2 find the meeting point in the ring.
Step two, find the entrance to the ring. Next step, when P1==p2, p2 through the number of nodes to 2x,p1 through the number of nodes X, set the ring has n nodes, p2 than P1 walk K-Ring has 2x=kn+x; Kn=x, you can see P1 actually walked the number of K-ring steps, then let P2 point to the list head, P1 position unchanged, p1,p2 every step until p1==p2; At this point the P1 points to the inlet of the ring.
Prove:
Note that the border must be controlled! Otherwise OJ is reported the error of access errors, through rate 0!
/*function ListNode(x){ this.val = x; this.next = null;}*/function EntryNodeOfLoop(pHead){ //只有1个节点或者0个节点直接返回null,因为这样不可能产生环 if(pHead == null || pHead.next == null) return null; let p1 = pHead; let p2 = pHead; //很巧妙,null是没有next的,否则oj会报访问越界错误,判断p2可走再p2.next可否走即可 while(p2 !==null && p2.next !== null) { p1 = p1.next; p2 = p2.next.next; if(p1 === p2) { p1 = pHead; while(p1!==p2) { p1 = p1.next; p2 = p2.next; } if(p1 === p2) return p1; } } return null;}
Sword means offer (23, 24, 25) the smallest number of K, the largest of successive sub-arrays, and the entry node of the ring in the linked list