当前位置:网站首页>Sword finger offer 11 Minimum number of rotation array

Sword finger offer 11 Minimum number of rotation array

2022-06-22 23:39:00 Front end plasterer

Move the first elements of an array to the end of the array , We call it rotation of arrays . Enter a rotation of an incrementally sorted array , Output the smallest element of the rotation array . for example , Array [3,4,5,1,2] by [1,2,3,4,5] A rotation of , The minimum value of the array is 1.

This problem is a simple sorting problem , stay js There are many sorting methods in

Method 1:sort Sort

	function minArray(n){
    
		return n.sort((a,b)=> a - b )[0]
	}

Method 2:Math.min Sort

	function minArray(n){
    
		return Math.min(...n);
	}

Method 3: Double pointer
analysis : Compare from both sides of the array to the middle , Find the smallest one in the array

	function minArray(n) {
    
       let result = [0];
       		for (let i = 0; i < n.length; i++) {
    
       		result = Math.min(result,n[i],n[n.length - 1 - i])
       }
       return result
    }   

Method 4: Dichotomy
analysis : Compare the size of the first two numbers and the middle number by comparison , Then cycle through the comparison , Finally determine the minimum number in the array

	  function minArray(n) {
    
            let left = 0;
            let right = n.length - 1;
            while(left < right){
    
                let flag = Math.floor((left + right) / 2);
                console.log(flag)
                if(n[left] > n[flag]){
    
                    right = flag
                }else if(n[right] < n[flag]){
    
                    left = flag + 1;
                }else{
    
                    right --;
                }
            }
            return n[left];
        }  

原网站

版权声明
本文为[Front end plasterer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222051389649.html