每日三题//什么是二分查找?
1.两个链表中的第一个公共节点:
第一种:哈希表存数据,另一个链表进行判断
var getIntersectionNode = function(headA, headB) {
const map=new Map()
let node = headA
while(node){
map.set(node,true)
node=node.next
}
node=headB
while(node){
if(map.has(node)) return node
node=node.next
}
return null
第二种:(两个链表加起来长度一样,如果不同继续,相同返回
var getIntersectionNode = function(headA, headB){
if(!headA||!headB){
return null
}
var a=headA,b=headB;
while(a!=b){
a=a?a.next:headB
b=b?b.next:headA
}
return a
}
2.在排序数组查找数字i出现的次数
排序是关键,如果等于目标值了,出现一次以上的就是一段,直接计算长度
暴力解法
var search = function(nums, target) {
var sum =0
for(var i=0;i<nums.length;i++){
if(nums[i]==target){
sum++
}
}
return sum
};
从两边向中间
var search = function(nums,target){
if(!nums.length) return 0
let left=0
right = nums.length-1
while(nums[left]!==target && left<nums.length){
++left
}
while(nums[right]!=target && right>=0){
--right
}
return left<=right?right-left+1:0
}
// 二分查找
var search = function(nums,target){
const length =nums.length
let start =-1
end=-1
let left=0;
right=length-1
while(left<=right){
let mid=Math.floor((left+right)/2);
if(nums[mid]==target){
start=mid
right=mid-1
}else if(nums[mid]>target){
right = mid -1
}else{
left = mid+1
}
}
left =0;
right = length-1
while(left<=right){
let mid=Math.floor((left+right)/2);
if(nums[mid]==target){
end = mid
left = mid+1
} else if(nums[mid]>target){
right=mid-1
}else{
left =mid+1
}
}
return start<=end && start!=-1 ?end-start+1:0
}
3.0-n中缺失的数字
二分法
var missingNumber = function(nums) {
let left =0
right = nums.length-1
while(left<=right){
let mid = Math.floor((left+right)/2)
if(mid===nums[mid]){
left=mid+1
}else if(mid<nums[mid]){
right=mid-1
}
}
return left
};
2.直接想
var missingNumber =function(nums){
// 怎么理解
nums.push("x")
for(var i=0;i<nums.length;i++){
if(nums[i]!=i)
return i
}
}
4.what 二分查找?
详细:
二分查找引申
https://www.cnblogs.com/luoxn28/p/5767571.html
细节
https://www.cnblogs.com/kyoner/p/11080078.html