LC-Find All Numbers Disappeared in an Array
2018-01-22 15:31
253 查看
方法1:
方法2:
0,方法2的时间复杂度更小,是个更优秀的算法
1,方法2中,首先获得index,也就是表中存在的元素所对应的位置,类hash的方式。
2,方法2将表中所有的存在元素对应的位置的值全部置为负值,这样最后返回表中不为负值的位置即可, 因为该位置的数值不为负说明对应位置的数字不存在与表中。
class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ hash = [] res = [] length = len(nums) for i in range(length): hash.append(0) for i in range(length): hash[nums[i]-1] +=1 for i in range(length): if hash[i] == 0: res.append(i+1) return res Sol = Solution() print Sol.findDisappearedNumbers([4,3,2,7,8,2,3,1])
方法2:
class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ # For each number i in nums, # we mark the number that i points as negative. # Then we filter the list, get all the indexes # who points to a positive number for i in xrange(len(nums)): index = abs(nums[i]) - 1 nums[index] = - abs(nums[index]) return [i + 1 for i in range(len(nums)) if nums[i] > 0]
0,方法2的时间复杂度更小,是个更优秀的算法
1,方法2中,首先获得index,也就是表中存在的元素所对应的位置,类hash的方式。
2,方法2将表中所有的存在元素对应的位置的值全部置为负值,这样最后返回表中不为负值的位置即可, 因为该位置的数值不为负说明对应位置的数字不存在与表中。
相关文章推荐
- 448. [LeetCode]Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Leetcode学习(19)—— Find All Numbers Disappeared in an Array
- 448. Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array(哈希表)
- 【LeetCode-448】 Find All Numbers Disappeared in an Array(C++)
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- leetcode448 Find All Numbers Disappeared In An Array Java
- leetcode-448-Find All Numbers Disappeared in an Array
- LeetCode No.448 Find All Numbers Disappeared in an Array
- 笔试题7. LeetCode OJ (7) Find All Numbers Disappeared in an Array
- LeetCode--Find All Numbers Disappeared in an Array(找到数组中未出现的数字)
- leetcode之 Find All Numbers Disappeared in an Array 问题
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- LeetCode Find All Numbers Disappeared in an Array
- leetcode 448 Find All Numbers Disappeared in an Array
- leetcode: Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array