classSolution { public: intdominantIndex(vector<int>& nums){ if (nums.size() == 0) return-1; if (nums.size() == 1) return0; int max_index = 0; bool flag = true; for (int i=1;i<nums.size();i++){ if (nums[max_index] > nums[i]){ if (flag) flag = nums[max_index] >= 2 * nums[i]; } else{ flag = nums[i] >= 2 * nums[max_index]; max_index = i; }
} if (!flag) return-1; elsereturn max_index; } };
Python3 实现如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defdominantIndex(self, nums: List[int]) -> int: if len(nums)== 0: return-1 if len(nums) == 1: return0 max_index = 0 flag = True for i in range(1,len(nums)): if nums[max_index] > nums[i]: if flag: flag = nums[max_index] >= 2 * nums[i] else: flag = nums[i] >= 2 * nums[max_index] max_index = i ifnot flag: return-1 else: return max_index