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

leetcode-136-easy

时间:2022-10-19 07:49:15浏览次数:53  
标签:set nums int singleNumber num 136 easy leetcode

Single Number
思路一: 用 set 过滤,剩下唯一一个就是目标数字

public int singleNumber(int[] nums) {
    Set<Integer> set = new HashSet<>();

    for (int num : nums) {
        if (set.contains(num)) {
            set.remove(num);
        } else {
            set.add(num);
        }
    }

    return set.iterator().next();
}

思路二: 用位操作符 XOR,出现两次的数字会相互抵消,刚好剩下就是目标数字

public int singleNumber(int[] nums) {
    int n = 0;
    for (int i = 0; i < nums.length; i++) {
        n ^= nums[i];
    }
    return n;
}

标签:set,nums,int,singleNumber,num,136,easy,leetcode
From: https://www.cnblogs.com/iyiluo/p/16804868.html

相关文章

  • leetcode-202-easy
    HappyNumber思路一:happynumber的结果完全分类,就两种情况最后的值为1进入循环(用map记录)publicbooleanisHappy(intn){Set<Integer>set=newHash......
  • leetcode-141-easy
    LinkedListCycle思路一:用set记录每个节点的hashCode,如果遇到重复,说明是循环publicbooleanhasCycle(ListNodehead){Set<Integer>set=newHashSet<>();......
  • leetcode-344-easy
    ReverseString思路一:首尾互换publicvoidreverseString(char[]s){intmid=s.length/2;intbegin=0;intend=s.length-1;while(beg......
  • leetcode-263-easy
    UglyNumber思路一:从数字中依次去除2,3,5,查看剩余的值是否为1publicbooleanisUgly(intn){if(n==0)returnfalse;while(n%2==0){n/......
  • leetcode-217-easy
    ContainsDuplicate思路一:Set检测publicstaticbooleancontainsDuplicate(int[]nums){Set<Integer>set=newHashSet<>();for(intnum:nums){......
  • leetcode-709-easy
    ToLowerCase思路一:遍历,遇到A-Z范围内的char转换到对应a-z范围publicStringtoLowerCase(Strings){if(s==null||s.isEmpty())returns;int......
  • leetcode-415-easy
    AddString思路一:模拟加法运算,字符串前面填零publicStringaddStrings(Stringnum1,Stringnum2){intmax=Math.max(num1.length(),num2.length());nu......
  • leetcode-389-easy
    FindtheDifference思路一:xor两个字符串publiccharfindTheDifference(Strings,Stringt){charresult=0;for(inti=0;i<s.length();i++){......
  • leetcode-226-easy
    InvertBinaryTree思路一:递归,交换左右。这题比较出名,个人感觉面试的题目和实际工作中遇到的问题还是不太一样的,所以一点准备都不做就跑去面试,答不上来很正常。一般能力......
  • leetcode-219-easy
    ContainsDuplicateII思路一:for循环遍历,结果超时publicbooleancontainsNearbyDuplicate(int[]nums,intk){intleft=-1;for(inti=0;i<nums......