Java + Count重复数组来自int数组,而不使用任何Collection或其他中间数组

时间:2015-07-31 05:30:57

标签: java arrays collections duplicates

作为Java面试问题文件的一部分,我有以下问题需要解决。 但我有点想知道如何在没有任何Collection或中间数组的情况下实现它。

问题: - 在不使用任何Collection或其他中间数组

的情况下从int数组中计算重复项
Input values:- {7,2,6,1,4,7,4,5,4,7,7,3, 1}  

Output:- Number of duplicates values: 3
         Duplicates values: 7, 4, 1

我已经实施了以下解决方案,但没有完成一个。 有谁有想法?感谢。

public static void duplicate(int numbers[]) {

    for (int i = 0; i < numbers.length; i++) {

        boolean duplicate = false;
        int j = 0;

        while (j < i){

            if ((i != j) && numbers[i] == numbers[j]) {
                duplicate = true;
            }

            j++;
        }

        if (duplicate) {
            System.out.print(numbers[i] + " ");
        }
    }
}

10 个答案:

答案 0 :(得分:8)

解决此问题的最简单方法是首先对数组进行排序,然后在遇到它们时遍历计算重复项的数组:

int[] numbers = new int[]{7,2,6,1,4,7,4,5,4,7,7,3,1};
int temp = 0;

// I chose to do a bubble sort of the array,
// but you are free to use any method you wish (e.g. Arrays.sort)
System.out.print("Duplicates values: ");
for (int i=0; i < numbers.length; ++i) {
    for (int j=1; j < (numbers.length - i); ++j) {
        if (numbers[j-1] > numbers[j]) {
            temp = numbers[j-1];
            numbers[j-1] = numbers[j];
            numbers[j] = temp;
        }
    }
}


// walk through the sorted array and count duplicates
int numDup = 0, dupCount = 0;
int previous = -1;
for (int i=0; i < numbers.length; ++i) {
    if (numbers[i] == previous) {
        ++numDup;
        if (numDup == 1) {
            ++dupCount;
            if (dupCount == 1) {
                System.out.print(numbers[i]);
            }
            else {
                System.out.print(", " + numbers[i]);
            }
        }
    }
    else {
        previous = numbers[i];
        numDup = 0;
    }
}

System.out.println("\nNumber of duplicates values: " + dupCount);

<强>输出:

Duplicates values: 1, 4, 7
Number of duplicates values: 3

请注意,我的输出顺序与您的输出顺序相反,因为您需要先了解整个数组,然后才能知道有多少重复项。此外,我将指出此解决方案使用的唯一状态是输入数组本身,以及此处和那里的几个int变量。

此代码已在IntelliJ中测试过,并且工作正常。

答案 1 :(得分:2)

同意Tim @ tim-biegeleisen。只是微小的改变。使用Arrays对数组进行排序。

public class DuplicateClass {

public static void main(String[] args) {
    int[] values = { 7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1 };
    duplicate(values);
}

public static void duplicate(int numbers[]) {
    Arrays.sort(numbers);
    int previous = numbers[0] - 1;
    ;
    int dupCount = 0;

    for (int i = 0; i < numbers.length; ++i) {
        if (numbers[i] == previous) {
            ++dupCount;
        } else {
            previous = numbers[i];
        }
    }
    System.out.println("There were " + dupCount + " duplicates in the array.");
}

}

答案 2 :(得分:1)

这些都是很好的答案。另一个是使用int / double并在遇到数字时设置它的位。如果数组的值小于32/64,则此方法有效,具体取决于您使用的类型。

以下是如何使用整数执行此操作的示例。

public class SetThoseBits{

    // 0000 0000 0000 0000 000 0000 0000 0000
    public static int data = 0; 

    public static void main(String [] args){

        // Gurantee that the numbers are less than 32
        int[] values = { 7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1 };
        duplicates(values);

    }

    public static void duplicates(int [] values){

        for(int i : values){

            if(testBit(i)){
                System.out.println("Duplicate :" + i);
            } else{
                setBit(i);
            }
            //printBits();
        }

        System.out.println("Finished!");
    }

    // Sets the bit at a specific position
    public static void setBit(int index){
        data = data | (1 << index);
    }

    // This function will test the bit at the index of the given integer
    // If it's set, it returns true
    public static boolean testBit(int index){
        return ((data & (1 << index)) != 0);
    }

    public static void printBits(){

        for (int x = 31; x >= 0; x--){
            if(testBit(x)){
                System.out.print("1");
            } else{
                System.out.print("0");
            }
        }
        System.out.println("0");
    }

}

我相信其他答案会更好地给出你的问题。但是作为替代方案证明这一点表明你正在动态地思考它。如果问题的要求稍微改变,这个答案可能更合适。

此外,如果您只需要尽可能小地跟踪重复项,您可以执行类似于上面的操作或使用java的BitSet类来使您的生活更轻松。

http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html

编辑:如果您创建一个包含像BitSet类这样的字节数组的函数,也可以使值高于64。对于这个确切的问题,考虑到不使用数组或集合的约束,这没有用。

答案 3 :(得分:0)

    int numbers[]={7,2,6,1,4,7,4,5,4,7,7,3, 1};
    String temp="";
    int count=0;
    Arrays.sort(numbers);

    for (int i = 0; i < numbers.length; i++) {

        boolean duplicate = false;
        for(int j = 0; j < numbers.length; j++) {
            if ((i != j) && numbers[i] == numbers[j]) {
                duplicate = true;
            }
        }

        if (duplicate) {
            if(!temp.contains(""+numbers[i]))
            {
            temp+=numbers[i]+", ";//adding a number if its duplicate
            count++;//counting unique duplicate number
            }
            System.out.print(numbers[i] + " ");
        }
    }
    System.out.println("\nDuplicates are: "+temp+" count: "+count);

<强>输出:

 Duplicates are: 1, 4, 7,  count: 3

答案 4 :(得分:0)

保留一个额外的变量来维持计数,再加上初始阶段的数组排序。

public static void main(String[] args) {
        int[] numbers = { 7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1 };
        Arrays.sort(numbers);
        System.out.println("Sorted Array is :: = " + Arrays.toString(numbers));

        int count = 0;
        int tempCount = 0; // to keep local count of matched numbers
        String duplicates = "";
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] == numbers[i - 1]) {
                if ((tempCount == 0)) { // If same number is repeated more than
                                        // two times, like 444, 7777
                    count = count + 1;
                    tempCount = tempCount + 1;
                    duplicates = duplicates.concat(Integer.toString(numbers[i])
                            + ",");
                }
            } else {
                tempCount = 0;
            }
        }

        System.out.println("No of duplicates :: = " + count);
        System.out.println("Duplicate Numbers are :: = " + duplicates);
    }

<强>输出

Sorted Array is :: = [1, 1, 2, 3, 4, 4, 4, 5, 6, 7, 7, 7, 7]
No of duplicates :: = 3
Duplicate Numbers are :: = 1,4,7,

答案 5 :(得分:0)

我认为,这也是一种计算方法:

public class App {
    public static void main(String[] args) {
        Integer[] intArr = { 7, 2, 6, 1, 4, 7, 4 };
        List<Integer> listInt = Arrays.asList(intArr);

        Map<Integer, Integer> map = new HashMap<>();
        Integer dupCount = 0;
        StringBuilder dupvalues = new StringBuilder();

        for (Integer integer : intArr) {
            int times = Collections.frequency(listInt, integer);
            if (map.containsKey(integer)) {
                dupvalues.append(integer).append(",");
                dupCount++;
            } else
                map.put(integer, times);
        }
        System.out.println("There were " + dupCount + " duplicates in the array. The value are : "+dupvalues);
    }
}

答案 6 :(得分:0)

这是我能想到的最简单的解决方案。我只是添加了一个额外的计数器,这样就可以忽略数组中仍有两次或多次重复的整数。

static int findNumber(int[] arr) 
{  
    int duplicateCounter = 0;

    System.out.print("Duplicates: ");

    for(int i = 0; i < arr.length; i++)
    {
        boolean duplicate = false;
        int numOfOccurrences = 1;

        for (int j = (i+1); j < arr.length; j++)
        {
            if (arr[i] == arr[j])
            {
                numOfOccurrences++;
                duplicate = true;
            }
        }
        if(numOfOccurrences == 2 && duplicate == true)
        {
            duplicateCounter++;
            System.out.print(arr[i] + " ");
        }
    }

    return duplicateCounter;
}

我的测试运行:Test run

输入:1,2,3,4,2,4,1,1,1

重复:2 4 1

重复次数:3

答案 7 :(得分:0)

有一种方法可以使用Math.abs。你应该检查标志是否正面。如果它是正面的,那么让它为负面。如果为负,则表示重复的数字或重复的数字。 示例:A [] = {1,1,2,3,2} I = 0; 检查A [abs(A [0])]的符号,即A [1]。 A [1]是正数,因此将其设为负数。 数组现在变为{1,-1,2,3,2}

I = 1; 检查A [abs(A [1])]的符号,即A [1]。 A [1]是负数,因此A [1]是重复。 然后将所有重复的数字放入列表中并打印列表的大小。

python中的代码是

    from astropy.extern.ply.cpp import xrange
def printrepeat(arr):
    print("The repeating elements are: ")
    list =[]
    for i in xrange(0,len(arr)):
        ch = abs(arr[i])

        if arr[ch] > 0:
            arr[ch] = (-1)*arr[ch];

        else: list.append(arr[ch])

    print(len(list))    




# driver code

arr = [1 , 3 , 2 , 2 , 1,3]
printrepeat(arr)            

解决方案2:选择2个指针

class Abc1{
    public static void main(String[] args) {

   int[] a = {1, 1, 2, 3, 2};
   countDuplicates(a);
}

    private static void countDuplicates(int[] a) {
        int c = 0 ;
        for(int  i = 0 ; i < a.length ; i++) {

            for(int j = i+1 ; j < a.length;j++) {
                if(a[i] == a[j]) {c++ ;}
            }//for
        }//for1
        System.out.println("dup => " + c);
    }

}

解决方案3:HashSet

class Abc1{
    public static void main(String[] args) {

  String a = "Gini Gina Protijayi";
   countDuplicates(a);
}

    private static void countDuplicates(String aa) {
        List<Character> list= new ArrayList<>();
       Set<Character> set = new HashSet<>();
       // remove all the whitespaces 
       String a = aa.replaceAll("\\s+","");
       for(  char ch : a.toCharArray()) {

           if(!set.contains(ch)) {
               set.add(ch);
           }//if
           else {if(!list.contains(ch) ) {list.add(ch);}      }
       }//for
       System.out.println("number of duplicate characters in the string =>" + list.size());
       System.out.println(list);
    }

}

解决方案:4(与解决方案1相同的概念,但代码是Java)

import java.util.ArrayList;
import java.util.List;

public class AA {

    public static void main(String[] args) {
         int a[] = {4, 2, 4, 5, 2, 3, 1};
         printRepeat(a);


    }

    private static void printRepeat(int[] a) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < a.length; i++) {
            if( a[Math.abs(a[i])]  > 0) {
                a[Math.abs(a[i])] = (-1)*  a[Math.abs(a[i])] ; 
            }//if
            else {
                System.out.println( "Duplicate numbers => " + Math.abs(a[i])         );
                list.add(Math.abs(a[i]));
                System.out.println("list => " + list);
                System.out.println("list.size() or the count of duplicates => " + list.size());
            }//else

        }//for

    }//print
    }

答案 8 :(得分:0)

下面的方法不使用任何集合,只需使用Arrays.sort()方法来帮助将数组默认排序为升序,例如array = [9,3,9,3,9]将排序为[3,3, 9,9,9]。如果输入[9,9,9,9,9],则预期结果为1,因为只有重复数为9。如果输入[9,3,9,3,9,255,255,1],则预期结果是3,因为重复的数字是3,9,255。如果输入[7,2,6,1,4,7,4,5,4,7,7,3,1],则预期结果是3,因为重复的数字是1,4,7。

public static int findDuplicateCountsInArray(int[] nums) {
    // Sort the input array into default ascending order
    Arrays.sort(nums);
    int prev = nums[0];
    int count = 0;
    // Recording a number already a repeated one
    // e.g [9,9,9] the 3rd 9 will not increase duplicate count again
    boolean numAlreadyRepeated = false;
    for(int i = 1; i < nums.length; i++) {
        if(prev == nums[i] && !numAlreadyRepeated) {
            count++;
            numAlreadyRepeated = true;
        } else if(prev != nums[i]) {
            prev = nums[i];
            numAlreadyRepeated = false;
        }
    }
    return count;
}

答案 9 :(得分:0)

这里我用JAVA编写了代码。输入的数字也被视为字符串。此问题也已添加到CODEWARS。我希望这个简单的解决方案对您有帮助

public class countingduplicates {
  public static void main(String[] args) {
    int i=0,j=0,c=0,a=0;
    String text="7261474547731";
    text=text.toLowerCase();

    for(i=0; i<text.length(); i++) {
      for(j=0; j<text.length(); j++) {
        if(text.charAt(i) == text.charAt(j)) { 
          c++;
        }
      }

      System.out.println(text.charAt(i) + " occured " + c + " times");
      if(c>1) {
        a++;
      }  

      String d = String.valueOf(text.charAt(i)).trim();
      text = text.replaceAll(d,"");
      c = 0;
      i = 0; //cause i have trimmed the string and by default i increases by 1, so i have to assign it =0
      j = 0; //cause i have trimmed the string and by default j increases by 1, so i have to assign it =0
    }
  System.out.println("Total count of Duplicates:" + a);
  }
}