leetcode 665

原題是 :

"判斷是否能最多修改一個數(shù),讓數(shù)組單調(diào)不減“

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).

Example 1:
Input: [4,2,3]
Output: True
Explanation: You could modify the first 
4
 to 
1
 to get a non-decreasing array.
Example 2:
Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.
Note: The n belongs to [1, 10,000].

思路是:

 一個數(shù)組,要能最多只修改一個數(shù),就實現(xiàn)單調(diào)不減,那么,當(dāng)出現(xiàn)一對前大后小的數(shù)的時候,要么是修改后一個數(shù)(比如需要把2改成4:4,4,4,2,5),要么是修改后一個數(shù)(比如需要把5改成2:1,2,5,2,3),就應(yīng)該能得到一個單調(diào)不減的數(shù)組。

另一個思路是:將前大后小的一對“問題數(shù)”,小的數(shù)那個與大的數(shù)再往前一個數(shù)進(jìn)行比較,
如果小數(shù) 比較大,則降低問題數(shù)中的大數(shù)(與小數(shù)相等);反之,如果小數(shù)比較小,則升高小數(shù)(與大數(shù)相等),經(jīng)過一番處理后,從原先的小數(shù)開始再找有沒有問題的數(shù)對,如果沒有,則返回真。

代碼是:

class Solution(object):
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        one,two = nums[:], nums[:]
        
        for i in xrange(len(nums) - 1):
            if nums[i] > nums[i+1]:
                one[i] = nums[i+1]
                two[i+1] = nums[i]
                break
        return one == sorted(one) or two == sorted(two)

學(xué)到的知識點:

1.sorted函數(shù)

sort()方法僅定義在list中,而sorted()方法對所有的可迭代序列都有效 :

sorted(iterable,key=None,reverse=False),返回新的列表,對所有可迭代的對象均有效
sort(key=None,reverse=False) 就地改變列表 reverse:True反序;False 正序

 print(sorted({8: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}))
 #輸出為:[2, 3, 4, 5, 8]

sorted(iterable,cmp,key,reverse)

 list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)]

print(sorted(list1,cmp = lambda x,y: cmp(x[0],y[0])))#按照第一個位置的字母序排序
#[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]

print(sorted(list1,cmp = lambda x,y: cmp(x[1],y[1])))#按照第二個位置的數(shù)字序排序 
 #[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]

key 是帶一個參數(shù)的函數(shù)

list.sort()和sorted()函數(shù)使用key參數(shù)來指定一個函數(shù),此函數(shù)將在每個元素比較前被調(diào)用。

例如通過key指定的函數(shù)來忽略字符串的大小寫

print(sorted("This is a test string from Andrew".split(), key=str.lower))
#輸出為:['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

也可以用Key 來比較:

sorted(student_tuples, key=lambda student: student[2])   # sort by age

#[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

student_tuples.sort(key=lambda x: x[2])

#[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

reverse參數(shù)

print(sorted(list1,reverse = True))#逆轉(zhuǎn)

#[('sara', 80), ('mary', 90), ('lily', 95), ('david', 90)]

2.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容