美文网首页
【LeetCode】面试题 08.03. 魔术索引(每日一题7/

【LeetCode】面试题 08.03. 魔术索引(每日一题7/

作者: 仍有不归期 | 来源:发表于2020-07-31 23:59 被阅读0次

打卡练手感,思想永不掉线

解题思路:

  • 魔术索引的意思就是 索引和值相等(index == value)

  • 定义res存储结果,初值为 - 1。

  • 遍历数组,遇到第一个魔术索引更新res并break。

  • 如果遍历完数组也没有找到魔术索引,那么保持初值-1不变。

java代码:

class Solution {
    public int findMagicIndex(int[] nums) {
        // 结果的初值设为-1
        int res = -1;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] == i) {
                res = i;
                break;
            }
        }
        return res;
    }
}

如有疑问,可通过 w20200730@protonmail.com 联系我

相关文章

网友评论

      本文标题:【LeetCode】面试题 08.03. 魔术索引(每日一题7/

      本文链接:https://www.haomeiwen.com/subject/qtwerktx.html