• LeetCode 1748. Sum of Unique Elements


    LeetCode 1748. Sum of Unique Elements (唯一元素的和)

    题目

    链接

    https://leetcode-cn.com/problems/sum-of-unique-elements/

    问题描述

    给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。

    请你返回 nums 中唯一元素的 和 。

    示例

    输入:nums = [1,2,3,2]
    输出:4
    解释:唯一元素为 [1,3] ,和为 4 。

    提示

    1 <= nums.length <= 100
    1 <= nums[i] <= 100

    思路

    恰好出现一次,就是只有单个,两个和两个以上都不用考虑。每个数字第一次遇见的时候,都是恰好出现一次,如果出现第二次再删除。

    这里设置一个map对,如果这个数不是key值,那就代表第一次出现,增加到和当中,并且给map添加一个<num,1>的值,表示该数字只出现一次。

    如果num在其中存在,且值为1,就代表之前出现过一次了,我们应该从答案中减去这个数字,并且更新为<num,2>,之后再碰到这个数就不用管了。

    复杂度分析

    时间复杂度 O(n)
    空间复杂度 O(n)
    

    代码

    Java

        public int sumOfUnique(int[] nums) {
            int ans = 0;
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int i = 0; i < nums.length; i++) {
                if (!map.containsKey(nums[i])) {
                    ans += nums[i];
                    map.put(nums[i], 1);
                } else if (map.get(nums[i]) == 1) {
                    ans -= nums[i];
                    map.put(nums[i], 2);
                }
            }
            return ans;
        }
    
  • 相关阅读:
    CSV
    矛与盾热血江湖实现喊话功能
    IDA 使用小结
    OD 命令行插件支持的命令
    Qt TreeView
    矛与盾内存数据的分析
    Windows 内核 I/O 端口操作
    矛与盾注入到目标进程
    Qt 多级menu
    C# 美元转中文
  • 原文地址:https://www.cnblogs.com/blogxjc/p/15914284.html
Copyright © 2020-2023  润新知