数组-(3 Sum of k)找到数组中和为k的3个数字

'''
在数组中找到3个元素的索引,满足和为k,且找到多个解
'''


class Solution:
    def call(self, nums, target):
        '''
        在nums中找到两个数,满足和为target
        :param nums: 
        :param target: 
        :return: 
        '''
        hashset = {}
        res = []
        for i, m in enumerate(nums):
            if target - m not in hashset:
                hashset[m] = i
            else:
                res.append([hashset[target - m], i])
        return res

    def call2(self, nums, k):
        '''
        在nums中找到3个数,满足和为k
        :param nums: 
        :param k: 
        :return: 
        '''
        if len(nums) < 3:
            return nums
        result = []
        for i in range(len(nums) - 1):
            target = k - nums[i]
            # 避免重复,从后面的数组开始寻找
            s = self.call(nums[i + 1:], target)
            if len(s) != 0:
                for p in s:
                    # ss = [nums[i], nums[i + p[0] + 1], nums[i + p[1] + 1]]
                    ss = [i, i + p[0] + 1, i + p[1] + 1]
                    if ss not in result:
                        result.append(ss)
        return result


s = Solution()
#找到和为-1
print(s.call2([-1, 0, 1, 2, -1, -4], -1))
#[[0, 2, 4], [2, 3, 5]]

 

posted @ 2019-03-15 22:13  jj千寻  阅读(144)  评论(0编辑  收藏  举报