在数组中查找非重复元素

时间:2014-12-31 13:46:06

标签: java arrays

我被困在以下程序中:

我有一个输入整数数组,只有一个非重复数,比如说{1,1,3,2,3}。输出应显示非重复元素,即2。

到目前为止,我做了以下事情:

public class Solution {

    public int singleNumber(int[] arr){
        int size = arr.length;
        int temp = 0;
        int result = 0;
        boolean flag = true;
        int[] arr1 = new int[size];

        for(int i=0;i<size;i++){
            temp = arr[i];
            for(int j=0;j<size;j++){
                if(temp == arr[j]){
                    if(i != j)
                    //System.out.println("Match found for "+temp);
                    flag = false;
                    break;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {

        int[] a = {1,1,3,2,3};
        Solution sol = new Solution();

        System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
    }
}

最好在数组中限制解决方案。避免使用集合,地图。

12 个答案:

答案 0 :(得分:7)

public class NonRepeatingElement {

public static void main(String[] args) {

    int result =0;
    int []arr={3,4,5,3,4,5,6};
    for(int i:arr)
    {
        result ^=i;
    }

    System.out.println("Result is "+result);
}

}

答案 1 :(得分:4)

因为这几乎肯定是一个学习练习,并且因为你非常接近正确地完成它,所以你需要改变它以使其工作:

  • 将<{1}} 的声明移到外部循环中 - 在外循环的每次迭代中,该标志需要设置为flag,并且它不会在外循环之外的任何地方使用。
  • 检查内部循环完成时的true - 如果flag仍为flag,则您找到了唯一的号码;归还它。

答案 2 :(得分:1)

From Above here is the none duplicated example in Apple swift 2.0

func noneDuplicated(){    
            let arr = [1,4,3,7,3]    
                 let size = arr.count  
                 var temp = 0  
                 for i in 0..<size{  
                   var flag = true  
                   temp = arr[i]  
                     for j in 0..<size{  
                     if(temp == arr[j]){  
                        if(i != j){  
                            flag = false  
                            break  
                        }   
                    }   
                }    
                if(flag == true){   
                print(temp + " ,")   
                }  
            }  
        }

// output : 1 , 4 ,7
// this will print each none duplicated 

答案 3 :(得分:0)

未经测试但应该正常工作

public class Solution {

    public int singleNumber(int[] arr){
        int size = arr.length;
        int temp = 0;
        int result = 0;
        boolean flag = true;
        int[] arr1 = new int[size];

        for(int i=0;i<size;i++){
            temp = arr[i];
            int count=0;
            for(int j=0;j<size;j++){
                if(temp == arr[j]){
                    count++;
                }
            }
            if (count==1){
               result=temp;
               break;
            }
        }
        return result;
    }

答案 4 :(得分:0)

尝试:

public class Answer{
   public static void main(String[] args) {
    int[] a = {1,1,3,2,3};
    int[] b =new int[a.length]; 
    //instead of a.length initialize it to maximum element value in a; to avoid
    //ArrayIndexOutOfBoundsException
    for(int i=0;i<a.length;i++){
      int x=a[i];
      b[x]++;
    }
     for(int i=0;i<b.length;i++){
       if(b[i]==1){
       System.out.println(i); // outputs 2
       break;
       }
     }
   }
}

PS:我对java感到很陌生,我通常会在C中编码。

答案 5 :(得分:0)

我有一个独特的答案,它基本上采用你在数组的外部for循环中的当前数字并将其自身计时(基本上是2的幂的数字)。然后它经历并且每次它看到数字不等于double本身测试如果它在数组的末尾用于内部for循环,那么它就是一个唯一的数字,就好像它找到一个等于的数字它本身然后跳到内部for循环的末尾,因为我们已经知道一个数字不是唯一的。

public class Solution {

    public int singleNumber(int[] arr){
        int size = arr.length;
        int temp = 0;
        int result = 0;
        int temp2 = 0;
        int temp3 = 0;
        boolean flag = true;
        int[] arr1 = new int[size];

        for(int i=0;i<size;i++){
            temp = arr[i];
            temp2 = temp*temp;
            for(int j=0;j<size;j++){
                temp3 = temp*arr[j];
                if(temp2==temp3 && i!=j)
                    j=arr.length
                if(temp2 != temp3 && j==arr.length){
                    //System.out.println("Match found for "+temp);
                    flag = false;
                    result = temp;
                    break;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {

        int[] a = {1,1,3,2,3};
        Solution sol = new Solution();

        System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
    }
}

答案 6 :(得分:0)

谢谢@dasblinkenlight ...按照你的方法

public class Solution {

    public int singleNumber(int[] arr){
        int size = arr.length;
        int temp = 0;
        int result = 0;

        int[] arr1 = new int[size];

        for(int i=0;i<size;i++){
            boolean flag = true;
            temp = arr[i];
            for(int j=0;j<size;j++){
                if(temp == arr[j]){
                    if(i != j){
//                  System.out.println("Match found for "+temp);
                    flag = false;
                    break;
                    }
                }

            }
            if(flag == true)
                result = temp;
        }
        return result;
    }

    public static void main(String[] args) {

        int[] a = {1,1,3,2,3};
        Solution sol = new Solution();
        System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
    }
}

一个灾难性的错误并不是将if(i != j)的内容括在括号内。谢谢大家的回答。

答案 7 :(得分:0)

如果您正在为学习编码,那么您可以更有效地解决它。

  1. 使用合并排序快速排序对给定数组进行排序。 运行时间将为nlogn。
  2. 想法是使用二进制搜索。 直到找到所需元素所有元素首先出现在偶数索引(0,2,...)和下一次出现在奇数索引(1,3,...)。 在必需元素首次出现在奇数索引和下一次出现在偶数索引之后。
  3. 使用上述观察,您可以解决:

    a)找到中间指数,比如'mid'。

    b)如果'mid'是偶数,则比较arr [mid]和arr [mid + 1]。如果两者相同,那么在mid之前的'mid'之后所需的元素。

    c)如果'mid'是奇数,那么比较arr [mid]和arr [mid - 1]。如果两者相同,那么在mid之前的'mid'之后所需的元素。

答案 8 :(得分:0)

        /// for duplicate array 
        static void duplicateItem(int[] a){

                /*
                You can sort the array before you compare
                */

                int temp =0;
                for(int i=0; i<a.length;i++){
                    for(int j=0; j<a.length;j++){
                        if(a[i]<a[j]){
                            temp = a[i];
                            a[i] = a[j];
                            a[j] = temp;
                        }
                    }
                }

                int count=0;

                for(int j=0;j<a.length;j++) {

                    for(int k =j+1;k<a.length;k++) {

                        if(a[j] == a[k]) {

                            count++;
                        }

                    }


                    if(count==1){

                        System.out.println(a[j]);

                    }

                   count = 0;
                }

            }


    /* 

       for array of non duplicate elements in array just change int k=j+1; to int k = 0; in for loop

    */
    static void NonDuplicateItem(int[] a){

            /*
            You can sort the array before you compare
            */

            int temp =0;
            for(int i=0; i<a.length;i++){
                for(int j=0; j<a.length;j++){
                    if(a[i]<a[j]){
                        temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }
                }
            }

            int count=0;

            for(int j=0;j<a.length;j++) {

                for(int k =0 ;k<a.length;k++) {

                    if(a[j] == a[k]) {

                        count++;
                    }

                }


                if(count==1){

                    System.out.println(a[j]);

                }

               count = 0;
            }

        }

public class DuplicateItem {
    public static void main (String []args){
        int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
        duplicateItem(a);
        NonDuplicateItem(a);
    }

答案 9 :(得分:0)

    /// for first non repeating element in array ///
     static void FirstNonDuplicateItem(int[] a){

            /*
            You can sort the array before you compare
            */

            int temp =0;
            for(int i=0; i<a.length;i++){
                for(int j=0; j<a.length;j++){
                    if(a[i]<a[j]){
                        temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }
                }
            }

            int count=0;

            for(int j=0;j<a.length;j++) {
                //int k;
                for(int k =0; k<a.length;k++) {

                    if(a[j] == a[k]) {

                        count++;
                    }

                }


                if(count==1){

                    System.out.println(a[j]);
                    break;

                }

              count = 0;
            }

        }

public class NonDuplicateItem {
    public static void main (String []args){
        int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
        FirstNonDuplicateItem(a);
    }

答案 10 :(得分:0)

另一种简单的方法。

    public static void main(String[] art) {
    int a[] = { 11, 2, 3, 1,1, 6, 2, 5, 8, 3, 2, 11, 8, 4, 6 ,5};
    Arrays.sort(a);
    System.out.println(Arrays.toString(a));
    for (int j = 0; j < a.length; j++) {
        if(j==0) {
            if(a[j]!=a[j+1]) {
                System.out.println("The unique number is :"+a[j]);
            }
        }else
        if(j==a.length-1) {
            if(a[j]!=a[j-1]) {
                System.out.println("The unique number is :"+a[j]);
            }
        }else
        if(a[j]!=a[j+1] && a[j]!=a[j-1]) {
            System.out.println("The unique number is :"+a[j]);
        }
    }
}

快乐编码。

答案 11 :(得分:0)

使用多个循环,时间复杂度为O(n ^ 2),因此使用HashMap解决时间复杂度为O(n)的有效方法。请在下面找到我的答案,

`public static int nonRepeatedNumber(int [] A){

Map<Integer, Integer> countMap = new HashMap<>();
int result = -1;

for (int i : A) {
  if (!countMap.containsKey(i)) {
    countMap.put(i, 1);
  } else {
    countMap.put(i, countMap.get(i) + 1);
  }
}

Optional<Entry<Integer, Integer>> optionalEntry = countMap.entrySet().stream()
    .filter(e -> e.getValue() == 1).findFirst();

return optionalEntry.isPresent() ? optionalEntry.get().getKey() : -1;

} }`

相关问题