Single Number II

Given an integer array nums where every element appears three times except for one, which appears exactly onceFind the single element and return it.

Example 1:

Input: nums = {2,2,3,2}
Output: 3

Approach

Java


public class SingleNumberII {
    public static void main(String[] args) {
        int nums[] = { 2232 };
        System.out.println(singleNumber(nums));
    }

    static int singleNumber(int[] nums) {
        int first = 0, second = 0, third;
        int n = nums.length;

        // iterate till the end of array
        for (int i = 0; i < n; i++) {
            // update second
            second = second | (first & nums[i]);
            first = first ^ nums[i];
            third = ~(first & second);
            first = first & third;
            second = second & third;
        }
        return first;

    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int singleNumber(vector<int>& nums
{
    int first=0,second=0,third;
    int n=nums.size();

    //iterate till the end of array
      for(int i=0;i<n;i++)
       {
           //update second
           second=second|(first&nums[i]);
           first=first^nums[i];
           third=~(first&second);
           first=first&third;
           second=second&third;
       }
        return first;
        
}

int main()
{
    vector<int > nums ={2,2,3,2};
    cout<<singleNumber(nums);
    return 0;
}


No comments:

Post a Comment