美文网首页
【codewars】Find the odd int

【codewars】Find the odd int

作者: 王简书2009 | 来源:发表于2017-10-11 10:21 被阅读0次

    原贴地址
    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<Integer, Integer> 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<Integer, Integer> entry : map.entrySet()) {
                if (entry.getValue() % 2 != 0) {
                    result = entry.getKey();
                }
            }
            
            return result;
           
        }
    }
    

    相关文章

      网友评论

          本文标题:【codewars】Find the odd int

          本文链接:https://www.haomeiwen.com/subject/trgbyxtx.html