首页 > 其他分享 >秒杀removeDuplicates问题(Golang版本)

秒杀removeDuplicates问题(Golang版本)

时间:2024-04-22 17:58:01浏览次数:22  
标签:elements nums int res Golang 秒杀 removeDuplicates unique

周末食欲不振,拿一道简单难度的题找找感觉,题目如下:

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
Return k.
Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
    assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

一个简单的思路就是通过遍历数组把非重复的元素保存到一个新的数组里面,然后再利用golang内置的copy方法,修改nums为非重复的:

func removeDuplicates(nums []int) int {
   var res []int
   for i := 0; i < len(nums); i++ {
        if  i == len(nums) - 1 || nums[i] != nums[i + 1] {
            res = append(res, nums[i])
        }
   }

   copy(nums, res)
   fmt.Println(res)
   return len(res)
}

或者只是用一个map来保存一个不重复的元素标识集合:

func removeDuplicates(nums []int) int {
	seen := make(map[int]bool)
	    j := 0
	    for _, n := range nums {
	        if !seen[n] {
	            seen[n] = true
	            nums[j] = n
	            j++
	        }
	    }
	
	    return j
}

总结
由于golang的slice的删除比较麻烦, 所以我还是考虑用重新赋值的方式,很多时候我们必须深入到数据结构本身去思考赋值问题。

标签:elements,nums,int,res,Golang,秒杀,removeDuplicates,unique
From: https://www.cnblogs.com/freephp/p/18151111

相关文章

  • Golang一日一库之gjson
    官网https://github.com/tidwall/gjson一简介gjson实际上是get+json的缩写,用于读取JSON串二使用1.安装gogetgithub.com/tidwall/gjson2.使用packagemainimport("fmt""github.com/tidwall/gjson")funcmain(){json:=`{"name":{......
  • 转载Using Domain-Driven Design(DDD)in Golang
    转载自:https://dev.to/stevensunflash/using-domain-driven-design-ddd-in-golang-3ee5UsingDomain-DrivenDesign(DDD)inGolang#go#ddd#redis#postgresDomain-DrivenDesignpatternisthetalkofthetowntoday.Domain-DrivenDesign(DDD)isanapproachtosoft......
  • 短视频直播系统,实现高并发秒杀的多种方式
    方式一(改进版加锁)@ApiOperation(value="秒杀实现方式——Lock加锁")@PostMapping("/start/lock")publicResultstartLock(longskgId){//在此处加锁lock.lock();try{log.info("开始秒杀方式一...");finallonguserId=(int)(ne......
  • golang etcd键值存储系统
    目录存储配置文件watch命令在Go语言中,etcd是一个高可用的键值存储系统,它主要用于共享配置和服务发现。etcd由CoreOS团队开发,它是Kubernetes项目中用于存储所有集群数据的关键组件。etcd使用Raft协议来保持集群之间的数据一致性,并且提供了强一致性保证https://blog.csdn.net/jo......
  • golang+kafka
    目录1.安装JDK、Zookeeper、Scala、kafka2.启动kafka3.创建topics4.查看topics5.打开一个producer6.打开一个consumer7.测试发送和接收消息Windows下安装Kafka1.安装JDK、Zookeeper、Scala、kafka安装Kafka之前,需要安装JDK、Zookeeper、Scala。Kafka依赖Zookeeper,......
  • 基于K8s+Docker+Openresty+Lua+SpringCloudAlibaba的高并发秒杀系统——与京东淘宝同
    ​介绍基于K8s+Docker+Openresty+Lua+SpringCloudAlibaba的高并发高性能商品秒杀系统,本系统实测单台(16核32G主频2.2GHz)openresty(nginx)的QPS可高达6w并发,如果您需要应对100w的并发,则需要100w/6w=17台openresty服务器,17台服务器同时接收并处理这100w的并发流量呢?当然是商业......
  • centos7安装golang最新版1.21.1
    #先卸载旧的golangyumremovegolang#然后找到最新版本https://golang.google.cn/dl/#下载安装cd/usr/local/src wgethttps://golang.google.cn/dl/go1.21.1.linux-amd64.tar.gztar-zxvfgo1.21.1.linux-amd64.tar.gz-C/usr/local/#增加配置文件vim/etc/profi......
  • Golang交替打印奇偶数
    packagemainimport( "fmt" "sync")varwgsync.WaitGroupfuncmain(){ evenCh,oddCh:=make(chanbool,1),make(chanbool,1) deferclose(evenCh) deferclose(oddCh) wg=sync.WaitGroup{} wg.Add(1) goprintNumbersSequent......
  • 脑洞golang embed 的使用场景
    golang的embed的功能真是一个很神奇的功能,它能把静态资源,直接在编译的时候,打包到最终的二进制程序中。为什么会设计这么一个功能呢?我想和golang的崇尚简单的原则有关系吧。它希望的是一个二进制文件能走天下,那么如果你作为一个web服务器,还需要依赖一大堆的静态文件,终究不......
  • golang JSON序列化和反序列化
    目录JSON序列化(Marshaling)JSON反序列化(Unmarshaling)错误处理和注意事项在Go语言(通常被称为Golang)中,JSON(JavaScriptObjectNotation)是一种常用的数据交换格式。Go标准库提供了encoding/json包,使得JSON的序列化(将Go数据结构转换为JSON格式的字符串)和反序列化(将JSON格式的字符串......