当前位置:网站首页>go实现leetcode旋转数组
go实现leetcode旋转数组
2022-07-02 04:58:00 【Jimmy_jimi】
目标:旋转数组
给你一个数组,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。
结果产出:
这里先使用最简单的循环改变,执行结果显示超时,经行优化,k取模以后仍旧超时,考虑应该是操作数组浪费了太多时间。
func rotate(nums []int, k int)[]int {
for i :=0;i<k;i++{
a := nums[(len(nums)-1)]
for j := len(nums)-1;j>0;j--{
nums[j] = nums[j-1]
}
nums[0]=a
}
return nums
}
使用临时数组,计算出每个元素的位置,然后重新添加到新的数组中去。
这里遇到问题,leetcode一直检测失败,查看逻辑应该没有问题,然后在自己电脑上运行显示没有问题。这是因为他直接检测了nums数组,而不是对返回值经行检测。
func rotate(nums []int, k int)[]int {
var nums1 = make([]int,len(nums))
k = k%len(nums)
for j :=0;j<len(nums);j++ {
if j+k<len(nums) {
nums1[j+k]=nums[j]
}else {
nums1[(j+k)%len(nums)]=nums[j]
}
}
return nums1
}
修改以后
执行用时:28 ms, 在所有 Go 提交中击败了26.28%的用户
内存消耗:7.9 MB, 在所有 Go 提交中击败了45.76%的用户
func rotate(nums []int, k int){
var nums1 = make([]int,len(nums))
k %= len(nums)
for j :=0;j<len(nums);j++ {
if j+k<len(nums) {
nums1[j+k]=nums[j]
}else {
nums1[(j+k)%len(nums)]=nums[j]
}
}
for j :=0;j<len(nums);j++ {
nums[j] =nums1[j]
}
}
边栏推荐
- 农业生态领域智能机器人的应用
- Knowledge arrangement about steam Education
- Keil compilation code of CY7C68013A
- Hcip day 17
- MySQL table insert Chinese change? Solution to the problem of No
- Typescript function details
- Interview question: do you know the difference between deep copy and shallow copy? What is a reference copy?
- 正大美欧4的主账户关注什么数据?
- C# 图片显示占用问题
- idea自動導包和自動删包設置
猜你喜欢
Gin framework learning code
解析少儿编程中的动手搭建教程
Pit encountered in win11 pytorch GPU installation
Analyzing the hands-on building tutorial in children's programming
Ansible installation and use
ThinkPHP kernel work order system source code commercial open source version multi user + multi customer service + SMS + email notification
LeetCode-归并排序链表
ansible安装与使用
Embedded-c language-9-makefile/ structure / Consortium
数学知识(欧拉函数)
随机推荐
js面试收藏试题1
Case sharing | intelligent Western Airport
MMAP zero copy knowledge point notes
10 minute quick start UI automation ----- puppeter
Introduction to Luogu 3 [circular structure] problem list solution
Design and implementation of general interface open platform - (44) log processing of API services
Here comes the chicken soup! Keep this quick guide for data analysts
Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知
社交媒体搜索引擎优化及其重要性
Steam教育的实际问题解决能力
cs架构下抓包的几种方法
2022阿里巴巴全球数学竞赛 第4题 虎虎生威(盲盒问题、集卡问题)解决思路
Tawang food industry insight | current situation, consumption data and trend analysis of domestic infant complementary food market
Application of intelligent robot in agricultural ecology
Mysql重点难题(2)汇总
培养中小学生对教育机器人的热爱之心
Learn what definitelytyped is through the typescript development environment of SAP ui5
Keil compilation code of CY7C68013A
Interview question: do you know the difference between deep copy and shallow copy? What is a reference copy?
ThinkPHP kernel work order system source code commercial open source version multi user + multi customer service + SMS + email notification