-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
134b4df
commit 0199484
Showing
3 changed files
with
34 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import { pivotIndex } from './pivotIndex'; | ||
|
||
describe('724. Find Pivot Index', () => { | ||
test('pivotIndex', () => { | ||
expect(pivotIndex([1, 7, 3, 6, 5, 6])).toBe(3); | ||
expect(pivotIndex([1, 2, 3])).toBe(-1); | ||
expect(pivotIndex([2, 1, -1])).toBe(0); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
type PivotIndex = (nums: number[]) => number; | ||
|
||
/** | ||
* Accepted | ||
*/ | ||
export const pivotIndex: PivotIndex = (nums) => { | ||
// Calculate the total sum of the array | ||
const totalSum = nums.reduce((acc, num) => acc + num, 0); | ||
|
||
// Initialize the left sum as 0 | ||
let leftSum = 0; | ||
|
||
for (let i = 0; i < nums.length; i++) { | ||
// Check if the left sum is equal to the right sum | ||
if (leftSum === totalSum - leftSum - nums[i]) return i; | ||
|
||
// Update the left sum by adding the current element | ||
leftSum += nums[i]; | ||
} | ||
|
||
// If no pivot index is found, return -1 | ||
return -1; | ||
}; |