leetcode202快乐数(JAVA)(hashset)

class Solution {
    public boolean isHappy(int n) {
        if(n==1||n==-1)
            return true;
        
        HashSet<Integer>h=new HashSet<Integer>();
        
        int m=0;
        while(true)
        {
            while(n!=0)
            {
                m=m+(n%10)*(n%10);
                n/=10;
            }
            if(m==1)
                return true;
            else if(!h.add(m))
                return false;
            
            n=m;
            m=0;
        }
    }
}

笔记

1.hashset与hashmap区别:https://www.cnblogs.com/codercui/p/6841730.html

主要区别是hashmap存的是键值对而hashset存的是元素,hashmap不允许关键值key重复,hashset不允许元素重复。

2.定义hashset: HashSet<Integer> h = new HashSet<>();

3.add方法返回布尔量. boolean b1 = hashset1.add("111");若set中没有111,则返回true,否则返回false

相关文章:

  • 2021-08-16
  • 2021-08-26
  • 2021-11-09
  • 2021-05-30
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
猜你喜欢
  • 2021-11-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-05
  • 2021-06-20
相关资源
相似解决方案