herrDeng網內搜尋

自訂搜尋

Ads

2024年3月16日 星期六

Python dict C++陣列Prefix Sum解Leetcode 525 Contiguous Array


Python  dict C++陣列Prefix Sum解Leetcode 525 Contiguous Array
使用 Prefix sum 來計算 n0 中的 0 和 n1 中的 1。 使用容器記錄n1-n0的索引。
hash表 (C++ unordered_map, Python dict) 用於此任務。
第二種方法是從第一種方法修改而來的陣列版本,速度很快。python這有提供。
---
Use Prefix sum to count 0s in n0 & 1s in n1. Use a container to record the index for n1-n0.
A hash table (C++ unordered_map, Python dict) is used for this task.
2nd approach is an array version modified from the 1st one which is fast.
  1. class Solution:
  2. def findMaxLength(self, nums: List[int]) -> int:
  3. n=len(nums)
  4. n1=0
  5. n0=0
  6. maxLen=0
  7. mp={}
  8. mp[0]=-1
  9. for i in range(n):
  10. n1+=nums[i]
  11. n0=(i+1)-n1
  12. if (n1-n0) in mp:
  13. maxLen=max(maxLen, i-mp[n1-n0])
  14. else:
  15. mp[n1-n0]=i
  16. return maxLen

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章