leetcode中數學類/數組類題目

1.整數反轉

思路:兩種方法,1是把數字轉化爲字符串,用字符串倒序遍歷的方式,需要開闢額外空間。

2是用➗10取餘數的方法。

https://leetcode-cn.com/problems/reverse-integer/solution/hua-jie-suan-fa-7-zheng-shu-fan-zhuan-by-guanpengc/

2.三數之和

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        res=[]
        for i in range(len(nums)-2):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            left=i+1
            right=len(nums)-1
            while left<right:
                if nums[i]+nums[left]+nums[right]==0:
                    res.append([nums[i],nums[left],nums[right]])
                    while left < right and nums[left]==nums[left+1]:
                        left=left+1
                    while right>left and nums[right]==nums[right-1]:
                        right=right-1
                    left=left+1
                    right=right-1
                elif nums[i]+nums[left]+nums[right]>0:
                    while right>left and nums[right]==nums[right-1]:
                        right=right-1
                    right=right-1
                elif nums[i]+nums[left]+nums[right]<0:
                    while left < right and nums[left]==nums[left+1]:
                        left=left+1
                    left=left+1
        return res

3.合併排序的數組

思路:倒敘遍歷

class Solution(object):
    def merge(self, A, m, B, n):
        """
        :type A: List[int]
        :type m: int
        :type B: List[int]
        :type n: int
        :rtype: None Do not return anything, modify A in-place instead.
        """
        #倒敘遍歷
        index1=m-1
        index2=n-1
        index3=m+n-1
        while index1>=0 and index2>=0:
            if A[index1]<B[index2]:
                A[index3]=B[index2]
                index2=index2-1
            else:
                A[index3]=A[index1]
                index1=index1-1
            index3=index3-1
        #特殊情況,A=[0],m=0,B=[1],n=1的時候,走不到前面的while循環
        if index2!=-1:
            A[:index2+1]=B[:index2+1]
        return A

4.數組中的第k個最大元素

思路:

https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zhong-de-di-kge-zui-da-yuan-su-by-leetcode/

根據快速排序的思想,快速排序:取一箇中間值,小於這個中間值的放到左邊,大於這個中間值的放到右邊。如果中間值的index等於target的話,就找到了結果。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章