基于位计数按升序对数组进行排序

时间:2018-02-17 16:53:30

标签: java

请告诉我在按位数计算时,我应该按升序对数组进行哪些更改 考虑一个名为elements的n个十进制整数数组。我们想根据以下规则重新排列元素:

按二进制表示中的1的数字按升序对整数进行排序。例如,7→111和8→1000,因此8(在二进制中具有单个1)将在7之前排序(其具有二进制的三重1)。 在二进制表示中具有相同数量的1的两个或更多个整数通过递增十进制值来排序。例如,5→101和6→110在它们的二进制表示中都包含双1,因此5将在6之前排序,因为它具有较小的十进制值。

我哪里错了? 输入: 五 五 3 7 10 14 输出继电器: 3 五 10 7 14

代码:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Tester {

    /**
     * Complete the function below.
     * DONOT MODIFY anything outside this function!
     */
    static int[] rearrange(int[] elements) {
         int[] aux= new int[elements.length];
         int a;
        for (int i=0; i<elements.length; i++){
            int count = 0;

            a=elements[i];
             for(int k =0; k<32; k++){
            if( (a&1) == 1) { 
              count++; } 
              a = a >>> 1;
              } 

                aux[i]=count;
                System.out.println(aux[i]);
            //    System.out.println(elements[i]);
        }

       //System.out.println(aux);
        //System.out.println(elements);
        for (int i = 1; i < (elements.length); i++)
    {
                //System.out.println(aux[i]);
                //System.out.println(elements[i]);
        // use 2 keys because we need to sort both
        // arrays simultaneously
        int key1 = aux[i];
        int key2 = elements[i];
        int j = i-1;

        /* Move elements of arr[0..i-1] and aux[0..i-1],
           such that elements of aux[0..i-1] are
           greater than key1, to one position ahead
           of their current position */
        while (j >= 0 && aux[j] > key1)
        {
            aux[j+1] = aux[j];
            elements[j+1] = elements[j];
            j = j-1;
        }
        aux[j+1] = key1;
        elements[j+1] = key2;
        }
        //System.out.println(aux);
        return elements;
    }


    /**
     * DO NOT MODIFY THIS METHOD!
     */
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);

        int n = 0;
        n = Integer.parseInt(in.nextLine().trim());
        int[] elements = new int[n];
        int element;
        for (int i = 0; i < n; i++) {
            element = Integer.parseInt(in.nextLine().trim());
            elements[i] = element;
        }

        // call rearrange function
        int[] results =rearrange(elements);

        for (int i = 0; i < results.length; i++) {
        System.out.println(String.valueOf(results[i]));
        }
    }
}

3 个答案:

答案 0 :(得分:2)

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/*
 * Sort the integers in ascending order by the number of 1's in their binary
 * representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1
 * in binary) would be ordered before 7 (which has triple 1's in binary). Two or
 * more integers having the same number of 1's in their binary representations
 * are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both
 * contain double 1's in their binary representation, so 5 would be ordered
 * before 6 because it has the smaller decimal value.
 */

public class Solution {

public static void main(String[] args) {
    List<Integer> myList = new ArrayList<>();
    myList.add(5);
    myList.add(3);
    myList.add(5);
    myList.add(7);
    myList.add(10);
    myList.add(14);
    myList.add(6);      

    Solution s1 = new Solution();
    System.out.println("before: " + myList.toString());
    /*
     * for (Integer num : myList) { System.out.println("*** sNumber = " + num);
     * System.out.println("Binary = " + Integer.toBinaryString(num));
     * System.out.println("Number of one bits = " + Integer.bitCount(num)); }
     */
    System.out.println("after: " + s1.rearrangeList(myList).toString());

}

public List<Integer> rearrangeList(List<Integer> theList) {

    Collections.sort(theList, new Comparator<Integer>() {

        @Override
        public int compare(Integer num1, Integer num2) {
            /*
             * a negative integer, zero, or a positive integer as the first argument 
             * is less
             * than, equal to, or greater than the second.
             */
            int result = 0;
            if (num1 == num2) {
                result = 0;
            } else if (Integer.bitCount(num1) < Integer.bitCount(num2)) {// 5=101 and 
                                                                         // 7=111
                result = -1;
            } else if (Integer.bitCount(num1) > Integer.bitCount(num2)) {// 7=111 and 
                                                                         // 6=110
                result = 1;
            } else if (Integer.bitCount(num1) == Integer.bitCount(num2)) {// 5=101 
                                                                          // 10=1010
                result = (num1 < num2) ? -1 : 1;// sort in natural order
            }
            return result;
        }
    });

    return theList;
    }

}

答案 1 :(得分:0)

public static List<Integer> rearrange(List<Integer> elements){
    if(elements == null) {
        return null;
    }
    Collections.sort(elements, new sortByBinaryRep());
    Set<Integer> set = new LinkedHashSet<>(elements);
    return new LinkedList<>(set);
}

import java.util.Comparator;

public class sortByBinaryRep implements Comparator<Integer> {

    @Override
    public int compare(Integer num1, Integer num2) {
        String binaryRep1 = Integer.toBinaryString(num1);
        String binaryRep2 = Integer.toBinaryString(num2);
        int bits1 = countBits(binaryRep1);
        int bits2 = countBits(binaryRep2);

        if(bits1 == bits2) {
            return num1 - num2;
        }
        else {
            return bits1 - bits2;
        }
    }

    private int countBits(String a){
        int count = 0;
        for(char c: a.toCharArray()) {
            if(c == '1') {
                count++;
            }
        }
        return count;
    }
}

答案 2 :(得分:-1)

这是任何感兴趣的人的C#代码:

using System;

namespace ConsoleApp1
{
class Program
{
    static int[] rearrange(int[] elements)
    {
        Array.Sort(elements);

        int[] countOfOnesFromElements = new int[elements.Length];
        int currentElement;
        for (int i = 0; i < elements.Length; i++)
        {
            int countTheNumberOfOnes = 0;

            currentElement = elements[i];
            for (int k = 0; k < 32; k++)
            {
                if ((currentElement & 1) == 1)
                {
                    countTheNumberOfOnes++;
                }
                currentElement = currentElement >> 1;
            }

            countOfOnesFromElements[i] = countTheNumberOfOnes;
            Console.WriteLine(countOfOnesFromElements[i]);
        }
        for (int i = 1; i < (elements.Length); i++)
        {
            int key1 = countOfOnesFromElements[i];
            int key2 = elements[i];
            int j = i - 1;

            while (j >= 0 && countOfOnesFromElements[j] > key1)
            {
                countOfOnesFromElements[j + 1] = countOfOnesFromElements[j];
                elements[j + 1] = elements[j];
                j = j - 1;
            }
            countOfOnesFromElements[j + 1] = key1;
            elements[j + 1] = key2;
        }

        return elements;           
    }
    static void Main(string[] args)
    {
        int[] res;

        int _elements_size = 0;
        Console.WriteLine("Input the element size: ");
        _elements_size = Convert.ToInt32(Console.ReadLine());
        int[] _elements = new int[_elements_size];
        int _elements_item;

        for(int _elements_i = 0; _elements_i < _elements_size; _elements_i++)
        {
            Console.WriteLine("What is Element {0}? ", _elements_i);
            _elements_item = Convert.ToInt32(Console.ReadLine());
            _elements[_elements_i] = +_elements_item;
        }

        res = rearrange(_elements);
        Console.WriteLine("\r\nAll elements in order of binary");
        for(int res_i = 0; res_i < res.Length; res_i++)
        {
            Console.WriteLine(res[res_i]);               
        }
        Console.ReadLine();

    }
}

}