Home > Enterprise >  What's meaning of this? "nums[-1] = nums[n] = -∞"
What's meaning of this? "nums[-1] = nums[n] = -∞"

Time:11-17

May I ask what this mean?

nums[-1] = nums[n] = -∞

I saw it in leetcode 162:https://leetcode.com/problems/find-peak-element/

CodePudding user response:

First element of the array in most languages has index 0. Last element has index n-1.

If you try to access element before the first, by calling nums[-1] you would naturally get an "out of bounds" error or a segfault. Same for the element after the last: nums[n].

The author of the leetcode task suggests to "extend" the domain of the array indices in the following way:

def nums_get(i):
  return -∞ if i == -1 or i == len(nums) else nums[i]
  • Related