当前位置:网站首页>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]
}
}
边栏推荐
- Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知
- Super detailed pycharm tutorial
- Leetcode basic programming: array
- idea自动导包和自动删包设置
- 06 装饰(Decorator)模式
- Embedded-c language-8-character pointer array / large program implementation
- Video multiple effects production, fade in effect and border background are added at the same time
- LM09丨费雪逆变换反转网格策略
- DMA Porter
- Beginner crawler - biqu Pavilion crawler
猜你喜欢

Application of intelligent robot in agricultural ecology

2022-003arts: recursive routine of binary tree

VMware installation win10 reports an error: operating system not found

AcrelEMS高速公路微电网能效管理平台与智能照明解决方案智慧点亮隧道

Lay the foundation for children's programming to become a basic discipline

cs架构下抓包的几种方法

Steam教育的实际问题解决能力

Super detailed pycharm tutorial

Mathematical knowledge (Euler function)

Idea automatic package import and automatic package deletion settings
随机推荐
How to recover deleted data in disk
Use of typescript classes
Federal learning: dividing non IID samples according to Dirichlet distribution
Lm09 Fisher inverse transform inversion mesh strategy
Application of intelligent robot in agricultural ecology
Learn BeanShell before you dare to say you know JMeter
数据库问题汇总
Go Chan's underlying principles
Analyze the space occupied by the table according to segments, clusters and pages
Mysql database learning
Idea automatic package import and automatic package deletion settings
Summary of main account information of zhengdaliu 4
Mapping location after kotlin confusion
Cultivate primary and secondary school students' love for educational robots
记录一次Unity 2020.3.31f1的bug
Beginner crawler - biqu Pavilion crawler
C# 基于MQTTNet的服务端与客户端通信案例
How to modify data file path in DM database
6.30 year end summary, end of student age
Domestic all Chinese automatic test software apifox