首页 > 其他分享 >leetcode-1748-easy

leetcode-1748-easy

时间:2022-10-30 11:56:03浏览次数:39  
标签:arr elements nums int num 1748 easy unique leetcode

Sum of Unique Elements

You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.

Return the sum of all the unique elements of nums.

 

Example 1:

Input: nums = [1,2,3,2]
Output: 4
Explanation: The unique elements are [1,3], and the sum is 4.
Example 2:

Input: nums = [1,1,1,1,1]
Output: 0
Explanation: There are no unique elements, and the sum is 0.
Example 3:

Input: nums = [1,2,3,4,5]
Output: 15
Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.
 

Constraints:

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

思路一: 符合条件的 nums[i] 范围在 [1, 100],用数组做映射

public int sumOfUnique(int[] nums) {
	int[] arr = new int[100];

	for (int num : nums) {
		if (arr[num - 1] > 0) {
			arr[num - 1] = -1;
		} else if (arr[num - 1] == 0) {
			arr[num - 1] = num;
		}
	}

	int result = 0;
	for (int i : arr) {
		if (i > 0) {
			result += i;
		}
	}

	return result;
}

标签:arr,elements,nums,int,num,1748,easy,unique,leetcode
From: https://www.cnblogs.com/iyiluo/p/16840877.html

相关文章

  • leetcode102-二叉树的层序遍历
    102.二叉树的层序遍历有两种实现方法。第一种是递归,第二种是队列实现。第一种是看了别人的代码写出来的,第二种是自己写的。这道题的不能直接把遍历得到的数字直接塞进res......
  • EasyExcel导出Date类型格式处理
    EasyExcel导出Date类型格式处理​ 如果在导出的excel中有date时间类型的字段,直接导出会报错org.apache.poi.ss.usermodel.Cell.setCellValue(Ljava/time/LocalDateTime;)......
  • 刷题 LeetCode二叉树2
    代码随想录LeetCode102.二叉树的层序遍历carl二叉树遍历#层序遍历#队列#广度优先思路队首是待访问节点,每访问一个节点,将其左子和右子加入队列细节如何知道某......
  • LeetCode 题解 | 1. 两数之和 Javascript 版
    题目给定一个整数数组nums 和一个整数目标值target,请你在该数组中找出和为目标值target 的那 两个 整数,并返回它们的数组下标。你可以假设每种输入只会对应一个......
  • LeetCode 题解 | 3. 无重复字符的最长子串 Javascript
    /***@param{string}str*@returnsnumber*思路:1.start与range组合成一个窗口,窗口内的子串就是当前最长不重复的字符串*2.range每次循环递增*......
  • LeetCode 题解|6. Z 字形变换
    /***@param{string}s*@param{number}numRows*@return{string}*/varconvert=function(s,numRows){//存储结果constrows=[];//指针下一......
  • LeetCode 题解|9. 回文数
    /***@param{number}x*@return{boolean}*/varisPalindrome=function(x){if(x<0){returnfalse;}letnum=x;letreverse=0;wh......
  • LeetCode 题解|7. 整数反转
    /***@param{number}x*@return{number}*/varreverse=function(x){letres=0;while(x!=0){res=res*10+(x%10);//划重点......
  • #yyds干货盘点# LeetCode 腾讯精选练习 50 题:旋转链表
    题目:给你一个链表的头节点head,旋转链表,将链表每个节点向右移动 k 个位置。 示例1:输入:head=[1,2,3,4,5],k=2输出:[4,5,1,2,3]示例2:输入:head=[0,1,2],k=4输出......
  • #yyds干货盘点# LeetCode 腾讯精选练习 50 题:不同路径
    题目:一个机器人位于一个mxn 网格的左上角(起始点在下图中标记为“Start”)。机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finis......