xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

LeetCode 寻找数组的中心下标算法题解 All In One

LeetCode 寻找数组的中心下标算法题解 All In One

724. Find Pivot Index

  1. 寻找数组的中心下标

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-12-28
 * @modified
 *
 * @description 724. Find Pivot Index
 * @description 724. 寻找数组的中心下标
 * @difficulty Easy
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/find-pivot-index/
 * @link https://leetcode.cn/problems/find-pivot-index/
 * @solutions
 *
 * @best_solutions
 *
 */

export {};

const log = console.log;

function pivotIndex(nums: number[]): number {
  let len = nums.length;
  if(!len) {
    return 0;
  } else {
    let index = 0;
    while(len) {
      const left = nums.slice(0, index).reduce((a,b) => a +=b, 0);
      // ✅ index + 1 
      const right = nums.slice(index + 1).reduce((a,b) => a +=b, 0);
      if(left === right) {
        //break;
        return index;
      }
      index += 1;
      len -= 1;
    }
    return -1;
  }
};


// 测试用例 test cases
const testCases: TestCasesI = [
  {
    input:[1,7,3,6,5,6],
    result: 3,
    desc: 'value equal to 3',
  },
  {
    input: [1,2,3],
    result: -1,
    desc: 'value equal to -1',
  },
  {
    input: [2,1,-1],
    result: 0,
    desc: 'value equal to 0',
  },
];

for (const [i, testCase] of testCases.entries()) {
  const result = pivotIndex(testCase.input);
  log(`test case i result: \n`, result === testCase.result  ? `passed ✅` : `failed ❌`, result);
  // log(`test case i =`, testCase);
}

// npx ts-node ./724\ find-pivot-index.ts

https://leetcode.cn/problems/find-pivot-index/

https://leetcode.com/problems/find-pivot-index/

refs

https://leetcode.com/study-plan/leetcode-75/?progress=xl5bhjoe

https://leetcode.cn/leetbook/read/top-interview-questions/xmlwi1/



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(18)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
历史上的今天:
2021-12-28 Mona Lisa with pure CSS (image to CSS)
2021-12-28 js 事件循环 & 宏任务 & 微任务 All In One
2020-12-28 bash copy multi files
2020-12-28 Linux bash fi
2020-12-28 docker-compose All In One
2020-12-28 Oh My Zsh & zsh All In One
2020-12-28 Docker in Action All In One
点击右上角即可分享
微信分享提示