Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中查找数组中出现的所有奇数元素_Java_Arrays - Fatal编程技术网

如何在Java中查找数组中出现的所有奇数元素

如何在Java中查找数组中出现的所有奇数元素,java,arrays,Java,Arrays,我试图找到数组中出现奇数次的所有元素。我计算了一点,但我的代码只返回正确的答案,如果只有一个数字出现奇数次。如果有两个或两个以上的奇数出现,我无法处理它。我的理解是,如果我们对元素进行位异或运算,就会得到一个奇数出现的元素。对于多个数字,我如何改进它 下面是我的代码: public class OddOccur { public int oddoccurence(int[] arr, int size) { int res = 0; int[] fin =

我试图找到数组中出现奇数次的所有元素。我计算了一点,但我的代码只返回正确的答案,如果只有一个数字出现奇数次。如果有两个或两个以上的奇数出现,我无法处理它。我的理解是,如果我们对元素进行位异或运算,就会得到一个奇数出现的元素。对于多个数字,我如何改进它

下面是我的代码:

public class OddOccur {
    public int oddoccurence(int[] arr, int size) {
        int res = 0;
        int[] fin = new int[size];

        for (int i = 0; i < size; i++) {
            res = res ^ arr[i];

        }
        return res;
    }

    public static void main(String args[]) {
        int[] arr = { 2, 5, 5, 2, 2, 3, 3, 3 };

        int n = arr.length;
        OddOccur obj = new OddOccur();

        System.out.println("odd occuring element is:"
                + obj.oddoccurence(arr, n));
    }
}
出现公共类异常{
公共整数奇数发生(整数[]arr,整数大小){
int res=0;
int[]fin=新的int[大小];
对于(int i=0;i
需要帮助来解决这个问题

public int oddoccurence(int[] arr, int size);
首先,可能有多个数字出现奇数次。如果该函数只返回一个
int
,则无法编写该函数并使其工作。您需要一个可以返回多个数字的函数

public int[] oddOccurrences(int[] array);
第二,不要试图变得聪明。使用XOR是“聪明的”。使用XOR无法找到简单的解决方案。这将是一个错综复杂的混乱局面。保持简单:

  • 计算每个数字出现的次数
  • 然后找出所有的奇数
  • 伪代码示例:

    // Map from numbers to counts. Assume the counts start at 0.
    Map<Integer, Integer> counts;
    
    for (number in array) {
        counts[number] += 1
    }
    
    // List of numbers that occur an odd number of items.
    List<Integer> oddNumbers;
    
    for (number, count in counts) {
        if (count % 2 != 0) {
            oddNumbers.add(number);
        }
    }
    
    //从数字映射到计数。假设计数从0开始。
    地图计数;
    for(数组中的数字){
    计数[数字]+=1
    }
    //出现奇数项的数字列表。
    列出数字;
    for(数字,计数中的计数){
    如果(计数%2!=0){
    添加(数字);
    }
    }
    
    可能是一篇旧文章。。但这里是我的答案

    在我看来,没有必要计算一个数字的出现次数来确定它是奇数还是非奇数。让我们使用一个数据结构,比如
    Set
    ,如果仍然没有prenent,只需将其添加到其中,如果已经存在,则将其删除

    大概是这样的:

    public int solution(int[] A){
    
        Set<Integer> unpaired = new HashSet<Integer>();
        for (int i = 0; i<A.length; i++){
            if (unpaired.contains(A[i])){
                unpaired.remove(new Integer(A[i]));
            }else{
                unpaired.add(A[i]);
            }
        }
    
    
        // all printed out values are odd
        for (Integer res : unpaired){
            System.out.println(res);
        } 
    }
    
    public int解决方案(int[]A){
    Set unpaired=新HashSet();
    
    对于(int i=0;i您实际上不需要记录每个整数的显示次数,只需要记录您是否看到了奇数次。因此,从您的数据结构(映射、哈希表、字典等)开始为空,这正确地反映了您没有看到奇数次的数字的状态。现在对于数组中的每个数字x,如果x在映射中,则删除它(现在您看到它偶数次),否则添加它

    下面是我使用HashMap的解决方案:

     public int solution(int[] A) {
    
            HashMap<Integer, Integer> map = new HashMap<>();
            HashSet<Integer> val = new HashSet<>();
            for (int i=0; i<A.length; i++){
            if (map.get(A[i]) == null) {
                map.put(A[i], 1);
            } else map.put(A[i], map.get(A[i])+1);
    
            if (map.get(A[i])%2 == 1) 
                val.add(A[i]);
                else val.remove(A[i]);
            }
    
            Iterator<Integer> itr = val.iterator();  
            return itr.next();  
    
        }
    
    public int解决方案(int[]A){
    HashMap=newHashMap();
    HashSet val=新的HashSet();
    
    对于(int i=0;i此解决方案的可编码性得分为100%。我们所做的只是初始化一个HashMap。HashMap的查找时间是O(1)常量时间,请参阅。由于我们只循环整个数组一次,因此最终得到O(N)时间,其中N是数组的长度

    如果HashMap中已经存在一个元素,那么我们可以删除它,因为我们已经找到了它对应的对。到最后,我们应该得到一个只有一对的HashMap。只需输出这个数字,您就完成了

    import java.util.*;
    class Solution {
        public int solution(int[] A) {
            int key;
            Map<Integer, Integer> unpaired = new HashMap<Integer, Integer>();
            for (int i = 0; i < A.length; i++){
                key  = A[i];
                Integer value = unpaired.get(key);
                if (value != null){
                    unpaired.remove(key); // Remove by key
                }
                else{
                    unpaired.put(key,0);
                }
            }
            for (Map.Entry<Integer, Integer> entry : unpaired.entrySet())
            {
                key =  entry.getKey();
            }
            return key;
        }
    }
    
    import java.util.*;
    类解决方案{
    公共int解决方案(int[]A){
    int键;
    Map unpaired=新HashMap();
    for(int i=0;i
    我认为使用
    映射
    存储出现次数是解决这个问题的正确方法,但是如果不同的数字太多,它需要更多的内存,使用
    位图
    也可以实现,并且需要更少的内存

    public static List<Integer> oddNumbers(int[] array, int size) {
            BitSet bitSet = new BitSet();
            for (int i = 0; i < size; i++) {
                bitSet.flip(array[i]);
            }
    
            List<Integer> resp = new ArrayList<>();
            for (int i = 0; i < bitSet.length(); i++) {
                if (bitSet.get(i)) {
                    resp.add(i);
                }
            }
            return resp;
        }
    
    publicstaticlist-oddNumbers(int[]数组,int-size){
    比特集比特集=新比特集();
    对于(int i=0;i
    测试用例是:

    @Test
    public void test_oddNumbers() throws Exception {
        int[] arr = {2, 5, 5, 2, 2, 3, 3, 3, 1, 7, 8, 9, 9, 9};
        List<Integer> resp = oddNumbers(arr, arr.length);
        assertTrue(resp.size() == 6);
        assertTrue(resp.containsAll(Arrays.asList(1, 2, 3, 7, 8, 9)));
    }
    
    @测试
    public void test_oddNumbers()引发异常{
    int[]arr={2,5,5,2,2,3,3,1,7,8,9,9};
    列表响应=奇数(arr,arr.length);
    assertTrue(分别为size()=6);
    assertTrue(分别包含所有数组(Arrays.asList(1,2,3,7,8,9));
    }
    
    //此解决方案的可信性得分为100%

    导入java.util.array

    类解决方案{

    public int solution(int[] A) {
        // write your code in Java SE 8
    
        Arrays.sort(A);
    
        int length = A.length;
    
        for (int i = 0, j = 1; i < length; i++) {
            if (j < length && A[i] == A[j]) {
                i++;
                j = j + 2;
            } else {
                return A[i];
            }
        }
    
        return 0;   
    }
    
    public int解决方案(int[]A){
    //用JavaSE8编写代码
    数组。排序(A);
    int length=A.length;
    对于(int i=0,j=1;i

    }

    问题很简单,只要对数组的所有元素使用位异或。原因是只有一个元素是不成对的。

    私有静态int-Odd(int[]a){
    
     private static int Odd(int[] a) {
            int unpaired;
            unpaired = a[0];
    
            for(int i = 1; i< a.length; i++){
                unpaired = unpaired ^ a[i]; // xor
            }
    
            return unpaired;
        }
    
    int未配对; 未配对=a[0]; for(int i=1;i
    公共类GetOddOccurrenceInArray{
    公共静态ArrayList GetOddOccurrence(int-arr[]){
    整数计数=0;
    ArrayList结果=新建ArrayList();
    HashMap hmap=newh
    
    public class GetOddOccurenceInArray {
        
        public static ArrayList<Integer> getOddOccurence(int arr[]){
            
            int count = 0;
            ArrayList<Integer> result = new ArrayList<>(); 
            HashMap<Integer, Integer> hmap = new HashMap();
    
            for(int num : arr){
                if(hmap.get(num) == null){
                    hmap.put(num, count+1); 
                }
                else
                    hmap.put(num, hmap.get(num)+1);
            }
              
            for (Entry<Integer,Integer> entry : hmap.entrySet()) { 
                if(entry.getValue()%2==1){
                    //System.out.println("number is "+entry.getKey());               
                    result.add(entry.getKey());
                }
    
            }
    
            return result;      
        }
        
        public static void main(String[] args){
            int arr[] = {1,2,2,2,3,3,3,3,4,5,6,6,7,8};
            ArrayList<Integer> occurred = getOddOccurence(arr);
            System.out.println("numbers occurred odd times : "+ occurred.toString());   
        }
    }
    
    fun oddOccurrencesInArray(array: IntArray) {
       
        var count = 0
        var arrayList = mutableListOf<Int>()
        array.sort() //sort the array
        var element = array[0]
        for (j in 1 until array.size) {
            if (element == array[j]) {
                count++
            } else {
                if (count == 0)
                    arrayList.add(array[j-1])
                count = 0
                element=array[j]
            }
        }
        if(count==0)
            arrayList.add(array[array.size-1])
        println("Given array: ${array.contentToString()} missing:${arrayList.toString()}")
    }
    
    public int solution(int[] A) 
    {
        Set<Integer> oddSet = new HashSet<>();
        
        for(int i = 0; i < A.length; i++)
        {
            if(!oddSet.contains(A[i]))
            {
                oddSet.add(A[i]);
            }
            else
            {
                oddSet.remove(A[i]);
            }
        }
        /* Based on the pre-conditions, we are sure that only one 
           remains here that is unique. So we just return that. */
        return oddSet.iterator().next();
    }