Leetcode 260. Single number III Java language

Source: Internet
Author: User

Given An array of numbers nums, in which exactly, elements appear only once and all the other elements appear exactly t Wice. Find the elements that appear only once. for Example:given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. Note:the Order of the result is not important. The above example, [5, 3] is also correct. Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity?

Test instructions: An array of elements have appeared two times, only two numbers appear once!!! Find out,!!!!!!.

Public class solution {    public int[] singlenumber (int[]  Nums)  {        int[] ret=new int[2];         if (nums==null | | &NBSP;NUMS.LENGTH&LT;4) return nums;        int norresult=0;         for (int i=0;i<nums.length;i++) {             norresult^=nums[i];         }        ///Find the 1 index location          int indexof1=index1 (Norresult);         for (int i =0;i<nums.length;i++) {            if (Is1 (nums[i ],INDEXOF1) ==1) {            ////a only with is 1 to do XOR or                  ret[0]^=nums[i];            }         }        ret[1]=norresult^ ret[0];        return ret;    }     public static int is1 (int num,int index) {    //// Determine if index is 1        num=num>>index;         return num&1;    }    public  Static int index1 (int num) {    /////determines the number of 1          int index=0;        while ((num&1) ==0) {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;      num=num>>1;             index++;        }         return index;    }}

PS: This can refer to the XOR idea of single number1. But now it needs to be divided into two parts to find. Refer to the sword for offer.

Leetcode 260. Single number III Java language

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.