Day3 appear in Java to solve k times and appear more than once

Title Description

The array only once appeared in a number of others have suffered several times k, find appeared only once and that the number of outputs.

Problem-solving approach

A method
using a hash table, each number as the key, scan array, a numeric value of +1 each occurrence corresponding to the key, the key 1 of the final output value of the hash table.

Method II
with no carry adder, a carry addition is not characterized by the same number k of k-ary adding the result is zero. The number array are converted to hexadecimal k, then adding the result from binary into decimal k, i.e. the number only appears once.

To exercise the problem in the second method

Code

public class 出现k次与出现1{
    public static void main(String[] args) {
        int [] arr={1,1,1,4,4,4,8,9,9,9,0,0,0,11,11,11};
        int k=3;   //出现k次
        int len=arr.length;
        char [][] arr2=new char[len][];
        int maxLen=0;
        //将10进制转为k进制,重点是进制转换和字符反转的妙用
        for(int i=0;i<len;i++){
            arr2[i]=new StringBuilder(Integer.toString(arr[i],k)).reverse().toString().toCharArray();
            if(maxLen<arr2[i].length)
                maxLen=arr2[i].length;
        }
        int []arr3=new int[maxLen];
        //做不进位加法
        for(int i=0;i<len;i++){
            for(int j=0;j<maxLen;j++){
                if(j>=arr2[i].length)
                    arr3[j]+=0;
                else
                    arr3[j]+=(arr2[i][j]-'0');
            }
        }
        int result=0;
        //将k进制转化为二进制
        for(int i=0;i<maxLen;i++){
            result+=(arr3[i]%k)*(int)(Math.pow(k,i));
        }
        System.out.println(result);
    }
}

Reference: Blue Bridge cup coaching sessions - "algorithm is beautiful"

Released three original articles · won praise 0 · Views 1339

Guess you like

Origin blog.csdn.net/weixin_44915222/article/details/104078749