0426: 14, and S is the number of two; 15, seeking 1 + 2 + 3 + ... + n, and

14, and S is the number of two:

Description Title
Enter a sorted array and incrementing a number S, find the two numbers in the array, and so that they are exactly S, and if a plurality of digits equal to S, the product of the output of the minimum number of two.
Output Description:

Corresponding to each test case, the output of two numbers, the first small output.

Note: Write your own add debugging out, but a lot of complexity, see rankings, a good compact
Method 1:

	
# -*- coding:utf-8 -*-
class Solution:
    def FindNumbersWithSum(self, array, tsum):
        # write code here
        # 因为是递增数组,所以最靠两边的一对就是积最小的
        l = []
        for x in array:
            l.append(tsum-x)
        for y in l:
            if y in array:
                return [tsum-y,y]
        return []

Method 2: own, too concise

# -*- coding:utf-8 -*-
class Solution:
    def FindNumbersWithSum(self, array, tsum):
        # write code here
        ans = []
        i = 0
        j = len(array)-1
        while i < len(array)-1 and j > 0:
            res = []
            if array[i] + array[j] == tsum:
                res.append(array[i])
                res.append(array[j])
                ans.append(res)
                i += 1
                j -= 1
            if array[i] + array[j] > tsum:
                j -= 1
            if array[i] + array[j] < tsum:
                i += 1
        if len(ans) == 0:
            return []
        else:
            return ans[0]

15, seeking 1 + 2 + 3 + ... + n, and

Description Title
seek 1 + 2 + 3 + ... + n, requires multiplication and division can not be used, for, while, if, else , switch, case and keywords such as conditional statement (A B:? C).

# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here
        return n and (n + self.Sum_Solution(n-1))
# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.sum = 0
    def Sum_Solution(self, n):
        # write code here
        def qiusum(n):
            self.sum += n
            n -= 1
            return n>0 and self.Sum_Solution(n)
        qiusum(n)
        return self.sum

Guess you like

Origin blog.csdn.net/Leia21/article/details/89575434