Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize region and search in LeetCode

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to achieve region and search in LeetCode. The content is concise and easy to understand. It will definitely make your eyes shine. I hope you can gain something through the detailed introduction of this article.

Given an array of integers nums, build a function to find the sum of the elements of the array from index i to j (i ≤ j), containing i, j. For example: input nums = [-2, 0, 3, -5, 2, -1], sumRange(0, 2) =1.

2

answer key

Idea: Dynamic programming, caching This problem can be directly used with the sum function, but it takes a long time. The intermediate state dp[i] represents the sum from 0-i, so the sum of i-j is required to be equal to dp[j]-dp[i-1], so first create an array record dp, and then calculate according to the desired range. Note here that dp[j]-dp[i-1] overflows when i=0, so dp has length len(numbers)+1, and the first element 0 means there is no value before i=0. class NumArray:

def __init__(self, nums: List[int]): if len(nums)==0: return self.dp = [0]*(len(nums)+1) self.dp[1]=nums[0] for i in range(2,len(nums)+1): self.dp[i] = self.dp[i-1]+nums[i-1]

def sumRange(self, i: int, j: int) -> int: return self.dp[j+1]-self.dp[i]

# Your NumArray object will be instantiated and called as such:# obj = NumArray(numbers)# param_1 = obj.sumRange(i,j) The above content is how to implement region and retrieval in LeetCode. Have you learned knowledge or skills? If you want to learn more skills or enrich your knowledge reserves, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report