leetCode Array -- 5.Largest Number At Least Twice of Others

扶醉桌前 提交于 2019-12-05 10:42:49

Problem five: Largest Number At Least Twice of Others

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.

Example 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.

Example 2:

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:

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

solution:

1.最开始想到的是用sort()函数来解决这个问题,但是需要注意两点:在sort函数中添加判断数字大小的函数,否则会将数字视为字符串,用最开始的数字进行排序;再一个就是在复制数组时,不能直接使用‘=’进行复制操作,因为这样其实传递的是数组地址,如果这样赋值,在对原先数组进行操作时,其实会对新建的数组进行修改。

123456789101112131415161718192021222324252627282930313233
function (a,b){         if (a>b) {             return 1;         }else if(a<b){              return -1         }else{             return 0;        }};var dominantIndex = function(nums) {    var nums_copy;    nums_copy = [];    for(var m = 0; m < nums.length; m++) {        nums_copy[m] = nums[m];    }    nums.sort(sequence);    if(nums.length == 1)        return 0;    if(nums[nums.length - 2] > 0) {        if(nums[nums.length - 1]/nums[nums.length - 2] >= 2) {            for(var i = 0; i < nums_copy.length; i++) {                if(nums_copy[i] == nums[nums.length -1])                    return i;            }        } else            return -1;    } else {        for(var n = 0; n < nums_copy.length; n++) {            if(nums_copy[n] == nums[nums.length -1])                return n;        }    }};

复杂度分析:
Time Complexity: O(n), n为nums的长度;

2.一开始以为上述方法比较简单,但实际写下来还有需要细节要注意,因此,先选出数组中的最大值,在与数组中的所有元素进行对比,当有元素大于nums[maxIndex]的1/2时,返回-1,否则返回该最大值下标。

123456789101112
var dominantIndex = function(nums) {    var maxIndex = 0;        for (var i = 0; i < nums.length; ++i) {            if (nums[i] > nums[maxIndex])                maxIndex = i;        }        for (var i = 0; i < nums.length; ++i) {            if (maxIndex != i && nums[maxIndex] < 2 * nums[i])                return -1;        }        return maxIndex;};

复杂度分析:
Time Complexity: O(n), n为nums的长度;

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!