leetcode每日一练

DATAWhale 第三个任务(2天)

排序
实现归并排序、快速排序、插入排序、冒泡排序、选择排序、堆排序(选做)

#插入排序
def insert_sort(arr):
	length=len(arr)
	for i in range(length):
		k=i
		for j in range(k,0,-1):
			if arr[j] < arr[j-1]:
				arr[j],arr[j-1]=arr[j-1],arr[j]

#快速排序
def quick_sort(arr,left,right):
	if left>right:
		return
	pivot=arr[left]
	i=left
	j=right
	while i<j:
		while i<j and arr[j] >= pivot:
			j-=1
		while i<j and arr[i] <= pivot:
			i+=1
		if i <j :
			arr[i],arr[j]=arr[j],arr[i]
		arr[left]=arr[i]
		arr[i]=pivot
		quick_sort(arr,left,i-1)
		quick_sort(arr,i+1,right)

二分查找
实现一个有序数组的二分查找算法
实现模糊二分查找算法(比如大于等于给定值的第一个元素)
对应的 LeetCode 练习题
Sqrt(x) (x 的平方根)
英文版:https://leetcode.com/problems/sqrtx/
中文版:https://leetcode-cn.com/problems/sqrtx/

class Solution(object):
    def mySqrt(self, x):
        if x==1 or x==0:
            return x
        else:
            left=0
            right=x
            while left<right:
                temp=(left+right)/2
                if int(temp)**2<=x and int((temp+1))**2>=x:                
                    if int((temp+1))**2==x:
                        temp=int((temp+1))
                    return(int(temp))
                    break        
                elif int(temp)**2<x and int(temp+1)**2<x:
                    left=temp             
                else:
                    right=temp

猜你喜欢

转载自blog.csdn.net/weixin_38966454/article/details/89302930