LeetCode-724. 尋找數(shù)組的中心索引

給定一個整數(shù)類型的數(shù)組 nums,請編寫一個能夠返回數(shù)組“中心索引”的方法。

我們是這樣定義數(shù)組中心索引的:數(shù)組中心索引的左側(cè)所有元素相加的和等于右側(cè)所有元素相加的和。

如果數(shù)組不存在中心索引,那么我們應該返回 -1。如果數(shù)組有多個中心索引,那么我們應該返回最靠近左邊的那一個。

示例 1:

輸入: 
nums = [1, 7, 3, 6, 5, 6]
輸出: 3
解釋: 
索引3 (nums[3] = 6) 的左側(cè)數(shù)之和(1 + 7 + 3 = 11),與右側(cè)數(shù)之和(5 + 6 = 11)相等。
同時, 3 也是第一個符合要求的中心索引。

示例 2:

輸入: 
nums = [1, 2, 3]
輸出: -1
解釋: 
數(shù)組中不存在滿足此條件的中心索引。

我的解法:遍歷數(shù)組,對數(shù)組左右兩邊相加對比,應該是復雜度最高的解法
代碼如下:

class Solution {
   public int pivotIndex(int[] nums) {
    for (int i=0; i<nums.length; i++) {
        int sumLeft = 0;
        int sumRight = 0;
        for (int j = 0; j < i; j++) {
            sumLeft += nums[j];
        }
        for (int k=i+1; k<nums.length; k++) {
            sumRight += nums[k];
        }
        if (sumLeft == sumRight) {
            return i;
        }
        }
        return -1;
    }
}

別人的方法:解決思路,求得數(shù)組總和,再遍歷數(shù)組

class Solution {
    public int pivotIndex(int[] nums) {
        int amount = 0 ;
        for(int i=0;i < nums.length;i++){
            amount = amount +nums[i];
        }
        int left = 0;
        int right = amount;
     for(int i=0;i < nums.length;i++){
            right -= nums[i]; 
            if (left == right){
                return i;
            }
            left += nums[i];
        }
        return -1;
    }
}

優(yōu)化后的方法

class Solution {
    public int pivotIndex(int[] nums) {
        int sum = 0;
        int left = 0;
        int right = 0;
        for(int i:nums){
            sum += i;
        }
        for(int i = 0; i < nums.length; i++){
            if(i == 0){
                left = 0;
            }else{
                left += nums[i-1];
            }
            right = sum - left - nums[i];
            if(left == right)
                return i;
        }
        return -1;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容