C#LeetCode刷题之#747-至少是其他数字两倍的最大数( Largest Number At Least Twice of Others)

版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/82470404

问题

在一个给定的数组nums中,总是存在一个最大元素 。

查找数组中的最大元素是否至少是数组中每个其他数字的两倍。

如果是,则返回最大元素的索引,否则返回-1。

输入: nums = [3, 6, 1, 0]

输出: 1

解释: 6是最大的整数, 对于数组中的其他整数,6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.

输入: nums = [1, 2, 3, 4]

输出: -1

解释: 4没有超过3的两倍大, 所以我们返回 -1.

提示:

nums 的长度范围在[1, 50].
每个 nums[i] 的整数范围在 [0, 99].


In a given integer array nums, there is always exactly one largest element.

Find whether the largest element in the array is at least twice as much as every other number in the array.

If it is, return the index of the largest element, otherwise return -1.

Input: nums = [3, 6, 1, 0]

Output: 1

Explanation: 6 is the largest integer, and for every other number in the array x,6 is more than twice as big as x.  The index of value 6 is 1, so we return 1.

Input: nums = [1, 2, 3, 4]

Output: -1

Explanation: 4 isn't at least as big as twice the value of 3, so we return -1.

Note:

nums will have a length in the range [1, 50].
Every nums[i] will be an integer in the range [0, 99].


示例

public class Program {

    public static void Main(string[] args) {
        int[] cost = null;

        cost = new int[] { 10, 15, 20 };
        var res = DominantIndex(cost);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static int DominantIndex(int[] nums) {
        //记录最大值和索引,最大值也可以不要,只存索引
        int max = int.MinValue;
        int index = -1;
        for(int i = 0; i < nums.Length; i++) {
            if(nums[i] > max) {
                max = nums[i];
                index = i;
            }
        }
        //i不用和自己比较,另外注意不要用除法,否则要处理数组中的0
        for(int i = 0; i < nums.Length; i++) {
            if(i != index && max < 2 * nums[i]) {
                return -1;
            }
        }
        return index;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

-1

分析:

显而易见,以上算法的时间复杂度为: O(n) 。

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/82470404
今日推荐