码迷,mamicode.com
首页 > 其他好文 > 详细

1426. Counting Elements

时间:2020-05-04 13:31:24      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:exp   out   HERE   etc   inpu   Plan   ted   ack   util   

package LeetCode_1426

import java.util.*

/**
 * 1426. Counting Elements
 * Given an integer array arr, count element x such that x + 1 is also in arr.
 * If there‘re duplicates in arr, count them separately.
 * Example 1:
 * Input: arr = [1,2,3] Output: 2, Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
Example 2:
Input: arr = [1,1,2] Output: 2, Explanation: 1 counted twice cause 2 is in arr.
 * */
class Solution {
    fun countElements(array: IntArray): Int {
        var ans = 0
        val set = HashSet<Int>()
        for (item in array) {
            set.add(item)
        }
        for (i in array.indices) {
            if (set.contains(array[i] + 1)) {
                ans++
            }
        }
        return ans
    }
}

 

1426. Counting Elements

标签:exp   out   HERE   etc   inpu   Plan   ted   ack   util   

原文地址:https://www.cnblogs.com/johnnyzhao/p/12826077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!