Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to find the central index of an array by leetcode

Shulou Source: shulou.com Published: 2022-06-01 13:20:47 09月17日 Update

Editor to share with you how leetcode to find the central index of the array, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

I. the content of the topic

Given an array nums of integer type, write a method that returns the array's "central index".

We define the central index of the array as follows: the sum of all elements on the left side of the central index of the array is equal to the sum of all elements on the right.

If the array does not have a central index, then we should return-1. If the array has more than one central index, then we should return the one closest to the left.

Example 1:

Enter:

Nums = [1,7,3,6,5,6]

Output: 3

Explanation:

The sum of the left number of index 3 (nums [3] = 6) (1 + 7 + 3 = 11) is equal to the sum of the right number (5 + 6 = 11).

At the same time, 3 is the first central index that meets the requirements.

Example 2:

Enter:

Nums = [1,2,3]

Output:-1

Explanation:

There is no central index in the array that meets this condition.

Description:

The length range of nums is [0, 10000].

Any nums [I] will be an integer in the range of [- 1000, 1000].

Second, the way to solve the problem

First calculate the sum of all elements in nums, and then calculate the left sum from left to right, if:

Left and * 2 + current element = all elements and

Returns the current element index, otherwise-1 is returned.

Code class Solution: def pivotIndex (self Nums: list)-> int: whole_sum = sum (nums) left_sum = 0 for i in range (len (nums)): if left_sum * 2 + nums [I] = whole_sum: return i else: left_sum + = nums [I] return-1if _ name__ = ='_ main__': S = Solution () nums1 = [1 7, 3, 6, 5, 6] ans1 = s.pivotIndex (nums1) print (ans1) nums2 = [1,2,3] ans2 = s.pivotIndex (nums2) print (ans2) nums3 = [- 1,-1,-1,-1,-1] ans3 = s.pivotIndex (nums3) print (ans3) nums4 = [- 1,-1,-1,-1,-1 0] ans4 = s.pivotIndex (nums4) print (ans4) these are all the contents of the article "how leetcode finds the central index of an array" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Index array element content article sum right integer example range interpretation input output not much code at the same time multiple most ideas methods Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux OPPO Reno Apple Docker NVidia