LeetCode算法题-Largest Number At Least Twice of Others(Java实现)

别再买成品了!手把手教你用0.5mm漆包线DIY高频空芯电感(附计算软件和脱漆技巧) 本文详细介绍了如何用0.5mm漆包线DIY高频空芯电感,涵盖从理论计算到实际绕制的完整流程。通过精确的几何参数控制和专业绕制工艺,读者可以制作出性能优异的高频电感,适用于射频匹配网络、LC谐振电路等场景。文章还提供了计算软件推荐和脱漆技巧,帮助爱好者轻松实现个性化电感制作。 阅读详情

这是悦乐书的第308次更新,第328篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第177题(顺位题号是747)。在给定的整数数组中,总有一个最大的元素。查找数组中的最大元素是否至少是数组中每个其他数字的两倍。如果是,则返回最大元素的索引,否则返回-1。例如:

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

输出:1

说明:6是最大的整数,对于数组x中的每个其他数字,6是x的两倍多。 值6的索引是1,所以我们返回1。


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

输出:-1

说明:4至少不是3的值的两倍,所以我们返回-1。


注意:

  • nums的长度在[1,50]范围内。

  • 每个nums [i]将是[0,99]范围内的整数。

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

题目的要求是返回最大数的索引,所以需要先将最大数找出来,并记录下其索引。然后在次遍历数组中的元素,将最大数之外的其他数都乘以2和最大数比较(在此处我是使用位移处理),如果大于就返回-1,如果其他元素都满足条件,就返回之前记录的最大数的索引。

public int dominantIndex(int[] nums) {
    int index = 0, max = 0;
    for (int i=0; i<nums.length; i++) {
        if (nums[i] > max) {
            max = nums[i];
            index = i;
        }
    }
    for (int i=0; i<nums.length; i++) {
        if (nums[i] != max && nums[i]<<1 > max) {
            return -1;
        }
    }
    return index;
}

03 第二种解法

我们还可以只使用一次循环来解决。并非需要使用每一个元素乘以2后再去和最大元素比较,只需要用第二大的数去比较就行,如果第二大的数不能满足条件,就可以直接做判断了。比如[2,3,4],3乘以2等于6大于4,不符合题目要求,就不需要比较2了。

public int dominantIndex(int[] nums) {
    int max = 0, second = 0, index = 0;
    for (int i=0; i<nums.length; i++) {
        if (nums[i] > max) {
            second = max;
            max = nums[i];
            index = i;
        } else if(nums[i] > second) {
            second = nums[i];
        }
    }
    return second<<1 <= max ? index : -1;
}

04 小结

算法专题目前已日更超过五个月,算法题文章177+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

Python开发MCP Client 全部例子只是MCP Client访问MCP Server的过程,那么这样其实就失去了MCP协议的创建的初衷,和大模型集成后才能发挥MCP最大的作用。 阅读详情

相关推荐

大疆OcuSync系统背后的黑科技:跳频扩频技术如何让你的无人机飞得更稳

本文深入解析了大疆OcuSync系统如何运用跳频扩频技术等先进无线通信方案,显著提升无人机在复杂环境下的飞行稳定性。系统通过跳频扩频与直接序列扩频技术协同工作,结合双频智能切换与多天线MIMO,有效对抗信号干扰与多径效应,确保控制指令与高清图传的可靠、低延迟传输,为用户带来更安心、更流畅的飞行体验。

ol7890123的博客 630

leetcode-747. Largest Number Greater Than Twice of Others

747. Largest Number Greater Than Twice of Others In a given integer arraynums, there is always exactly one largest element. Find whether the largest element in the array is at least twice ...

anchouman0644的博客 234

从拆解图看懂空心杯电机:有刷 vs 无刷内部结构全解析(附DIY注意事项)

本文深入解析有刷与无刷空心杯电机的内部结构差异,通过高清拆解图展示关键部件工艺特点,并分享实用的维护技巧和检测方法。重点对比两种电机在效率、寿命和适用场景上的优劣,为DIY爱好者提供详细的注意事项和操作指南。

xgboost6farmer的博客 523

【java】747. Largest Number At Least Twice of Others

问题原文点击打开链接这道题简单的不用思考..... public int dominantIndex(int[] nums) { int maxVal = Integer.MIN_VALUE; int pos = 0; for (int i = 0;i&lt;nums.length;i++){ if (nums[i] &...

amber804105的博客 254

华为S5700三层交换机VLAN配置避坑指南:为什么你的VLAN间无法互通?

本文针对华为S5700三层交换机VLAN间无法互通的典型故障,提供深度排障指南。文章从数据转发原理入手,系统梳理了从物理链路、VLAN配置、VLANIF接口状态、路由表到ARP表、MTU及安全策略等全链路检查点,并给出了清晰的排查命令与流程,帮助网络工程师快速定位并解决VLAN间路由问题,实现稳定互通。

tt34567的博客 875

光伏系统选型指南:5种主流MPPT算法优缺点对比(附选型流程图)

本文深入剖析了光伏系统中五种主流MPPT算法的核心原理与性能差异。通过对比扰动观察法、电导增量法、恒定电压法、模糊逻辑控制及人工智能算法在追踪精度、响应速度、实现成本与稳定性等方面的表现,为不同应用场景(如户用、工商业及大型电站)提供了清晰的选型决策流程图和实战指南,帮助工程师优化系统效率与投资回报。

weixin_29294597的博客 107

747. 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 th

繁城落叶 1370

在claude code中使用glm模型出现Unable to connect to Anthropic services的解决方案

本文主要介绍了在claude code中使用glm模型出现Unable to connect to Anthropic services的解决方案,希望能对使用claude code的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案

weixin_43178406的博客 13万+

【LeetCode】747. Largest Number At Least Twice of Others 至少是其他数字两倍的最大数 ---java实现

问题描述 在一个给定的数组nums中,总是存在一个最大元素 。 查找数组中的最大元素是否至少是数组中每个其他数字的两倍。 如果是,则返回最大元素的索引,否则返回-1。 示例 1: 输入: nums = [3, 6, 1, 0] 输出: 1 解释: 6是最大的整数, 对于数组中的其他整数, 6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.   示例 2: 输入: n...

wangrui1605的博客 435

Android实现TextToSpeech控件实现语音播报--朗读文字 (附完整源码)

Android实现TextToSpeech控件实现语音播报--朗读文字 (附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 1121

【机器学习】一文搞懂算法模型之:Transformer

必会算法模型之:Transformer

商务合作 | 面试培训 | 职场规划 ==>主页扫码 5610

largest number java_LeetCode算法题-Largest Number At Least Twice of Others(Java实现)

这是悦乐书的第308次更新,第328篇原创01 看题和准备今天介绍的是LeetCode算法题中Easy级别的第177题(顺位题号是747)。在给定的整数数组中,总有一个最大的元素。查找数组中的最大元素是否至少是数组中每个其他数字的两倍。如果是,则返回最大元素的索引,否则返回-1。例如:输入:nums = [3,6,1,0]输出:1说明:6是最大的整数,对于数组x中的每个其他数字,6是x的两倍多。 ...

weixin_39733821的博客 108

Python爬虫实战:用Playwright+Transformer做财经新闻事件驱动分析,我靠它抓住了算力政策的涨停机会

对我来说,这套系统最大的价值不是抓住了几次涨停,而是把“看新闻→分析→决策”的全流程自动化、量化了——不用再被股吧的情绪带偏,不用再熬夜刷新闻,而是用数据和模型做理性判断。更重要的是,搭建这套系统的过程,我吃透了Playwright动态爬虫、Transformer文本分析、量化数据对接这些核心技能,这些技能不管是做量化、做数据分析师,还是做其他领域的爬虫,都能用得上。现在打开PyCharm,跟着代码跑一遍,你也能从海量财经新闻里,挖出属于自己的事件驱动信号——与其靠感觉炒股,不如靠数据说话。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1394

[Leetcode] 747. Largest Number At Least Twice of Others

Problem: https://leetcode.com/problems/largest-number-at-least-twice-of-others/ class Solution { public int dominantIndex(int[] nums) { int max = 0; int max_idx = 0; for(in...

Renoler的博客 150

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

[LeetCode] 747. Largest Number At Least Twice of Others

In a given integer arraynums, 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,...

a0712104790的博客 80

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

leetcode 747. Largest Number At Least Twice of Others

很傻白甜的一道题。 class Solution { public int dominantIndex(int[] nums) { int max = Integer.MIN_VALUE; int index = 0; for(int i = 0;i<nums.length;i++){ if(nums[i]&gt...

xiaobailaji的博客 132

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

747. Largest Number At Least Twice of Others[Leetcode从零开刷]

题目来源: leetcode 题目 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

legalhighhigh的博客 260

Leetcode#747. 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, ...

xunalove的博客 337

【Lintcode】1053. Largest Number At Least Twice of Others

题目地址: https://www.lintcode.com/problem/largest-number-at-least-twice-of-others/description 给定一个数组AAA,寻找其最大值,并判断其是否至少是别的数字的两倍。如果是,则返回该最大值下标,否则返回−1-1−1。 代码如下: public class Solution { /** * @param nums: a integer array * @return: the index of th

数学、算法爱好者的博客 150

【Leetcode】747. Largest Number At Least Twice of Others

题目地址: https://leetcode.com/problems/largest-number-at-least-twice-of-others/ 给定一个长nnn数组AAA,保证存在唯一的最大值,问这个最大值是否不小于任一别的数字的两倍。如果不是则返回−1-1−1,否则返回这个最大值的下标。 代码如下: public class Solution { public int dominantIndex(int[] nums) { int max = Integer.MIN_VA

数学、算法爱好者的博客 185

leetcode747-Largest Number At Least Twice of Others

题目 给你一个整数数组 nums ,其中总是存在 唯一的 一个最大整数 。 请你找出数组中的最大元素并检查它是否 至少是数组中每个其他数字的两倍 。如果是,则返回 最大元素的下标 ,否则返回 -1 。 示例 1: 输入:nums = [3,6,1,0] 输出:1 解释:6 是最大的整数,对于数组中的其他整数,6 至少是数组中其他元素的两倍。6 的下标是 1 ,所以返回 1 。 分析 这个是一道很常规的题目,遍历数组找到最大值,然后检查每个元素和最大值之间的关系即可 public class largestN

我的程序人生 311

LeetCode-Largest Number At Least Twice of Others

LeetCode Java Largest Number At Least Twice of Others

坟头草一米七五 279

747. Largest Number At Least Twice of Others(数组)

https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/ 题目:判断最大数是否最少是次大数的2倍。 思路:直接求出最大值,次大值判断即可。 class Solution { public: int dominantIndex(vectorint>& nums) {

博客 422

【Array-easy】747. Largest Number At Least Twice of Others 最大数是其他数两倍以上

1. 题目原址 https://leetcode.com/problems/largest-number-at-least-twice-of-others/ 2. 题目描述 3. 题目大意 找到数组中最大的数字,如果他比其他所有的数组都大2倍以上,则返回最大元素的索引值,否则返回 - 1 4. 解题思路 首先找到数组中的最大元素和第二大元素以及最大元素的下标 最后比较最大元素是否是第二大元素...

想当厨子的程序媛 158

leetcode (Largest Number At Least Twice of Others)

Title:Largest Number At Least Twice of Others   747 Difficulty:Easy 原题leetcode地址:https://leetcode.com/problems/largest-number-at-least-twice-of-others/   1. 找到最大值并记录其下标,找到第二大值 时间复杂度:O(n),两次一层for循...

hsx1612727380的专栏 168
上一篇: LeetCode算法题-Min Cost Climbing Stairs(Java实现)
下一篇: LeetCode算法题-Shortest Completing Word(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值