【codewars】Find the odd int

原贴地址
https://www.codewars.com/kata/54da5a58ea159efa38000836/train/java

描述
Given an array, find the int that appears an odd number of times.

There will always be only one integer that appears an odd number of times.

代码模版

public class FindOdd {
    public static int findIt(int[] A) {
        return odd
    }
}

测试用例模版

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class FindOddTest {
    
  @Test
  public void findTest() {
    assertEquals(5, FindOdd.findIt(new int[]{20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5})); 
    assertEquals(-1, FindOdd.findIt(new int[]{1,1,2,-2,5,2,4,4,-1,-2,5})); 
    assertEquals(5, FindOdd.findIt(new int[]{20,1,1,2,2,3,3,5,5,4,20,4,5}));
    assertEquals(10, FindOdd.findIt(new int[]{10}));
    assertEquals(10, FindOdd.findIt(new int[]{1,1,1,1,1,1,10,1,1,1,1}));
    assertEquals(1, FindOdd.findIt(new int[]{5,4,3,2,1,5,4,3,2,10,10}));
    }
}

我的答案

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class FindOdd {
    public static int findIt(int[] A) {
        if (A == null || A.length < 1) {
            return 0;
        }
        
        Map map = new HashMap<>();
        for (int i = 0; i < A.length; i++) {
            int a = A[i];
            if (map.containsKey(a)) {
                map.put(a, map.get(a) +1);
            }else {
                map.put(a, 1);
            }
        }
        
        int result = 0;
        
        for (Entry entry : map.entrySet()) {
            if (entry.getValue() % 2 != 0) {
                result = entry.getKey();
            }
        }
        
        return result;
       
    }
}

你可能感兴趣的:(【codewars】Find the odd int)