LeetCode:找出出现一次的元素的加强版

Given a non-empty array of integers,every element appears three times except for one,
which appears exactly once.Find that single one.
Note:
Your algorithm should have a linear runtime complexity.Could you implement it without
using extra memory?

Example 1:
Input:[2,2,3,2]
Output:3

Example 2:
Input:[0,1,0,1,0,1,99]
Output:99

题目大意:
给定一个非空数组,除了某个元素只出现一次以外,其余每个元素均出现了三次.找出那个只出现一次的元素.
算法时间复杂度是线性的,并且不使用额外的辅助空间.
*/
package main

import (
	"fmt"
	"sort"
)

func singleNumber(nums []int)int{
	sort.Ints(nums)
	var i=2
	for ;i<len(nums);i+=3{
		if nums[i-2]!=nums[i-1]{
			break
		}
	}
	return nums[i-2]
}
func main(){
	fmt.Println( "求数组中出现一次的元素")
	nums:=[]int{0,1,0,1,0,1,99}
	fmt.Println(singleNumber(nums))
}
/*
找出出现一次的元素,其余的都是三个.

(1)通过遍历数组获取所有元素的和以及set内元素的和,set容器不会添加重复的元素;
(2)(3*ans-sum)/2即可,除以2是因为我们减去之后得到的是2倍的目标元素;

*/
#include <iostream>
#include <vector>
#include <set>
#include <numeric>

using namespace std;

class Solution{
public:
    int singlenumber(vector<int>& nums){
        set<int> res;
        for(auto& num:nums){
            res.insert(num);
        }
        long sum=accumulate(nums.begin(),nums.end(),0),
        ans=accumulate(res.begin(),res.end(),0);
        return (int)(3*ans-sum)/2;
    }
};
int main(int argc,char* argv[]){
    vector<int> nums={0,1,0,1,0,1,99};
    cout<<Solution().singlenumber(nums)<<endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路上的追梦人

您的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值