Leetcode 3Sum TypeError: tuple object does not support item assignment

Leetcode 3Sum TypeError: tuple object does not support item assignment

我收到类型错误:元组对象不支持第 result_dict[t] = 0 行的项目分配。我想检查我的 3Sum 逻辑是否正确,但是,我无法理解这个问题。

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        i = 0
        result = []
        my_dict = dict()
        result_dict = ()
        
        for i in range(len(nums)):
            my_dict[nums[i]] = i
        
        for j in range(len(nums) - 1):
            target = nums[j]
            
            for i in range(j+1, len(nums)):
                y = -target - nums[i]
                key_check = tuple(sorted((nums[j], nums[i], y)))
                if key_check in result_dict:
                    continue
                if  my_dict.get(y) and my_dict[y]!=i and my_dict[y]!=j:
                    #result.append([nums[j], nums[i], y])
                    t = tuple(sorted((nums[j], nums[i], y)))
                    result_dict[t] = 0

        
        for key in result_dict.keys():
            result.append(list(key))
        return result
        #return list(set([ tuple(sorted(t)) for t in result ]))
            

创建了一个带有空大括号 {} 的空字典。空括号 () 将创建一个基本上是不可变列表的元组。

result_dict = {}

将修复您的代码。