【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<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;
       
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第一阶段:存银行赚利息 2007年的时候,HSBC发布了一个新的储蓄帐户,叫HSBC Direct,类似于ING ...
    成长是刚需阅读 2,897评论 0 0
  • 夜风习习 蛙鸣如歌 风吹云动 是多情的云 还是绝情的月 云和月还是擦肩而过 一只乡下的蚊子 站在柳梢上企望 瘪瘪的...
    王逸闻阅读 248评论 0 0
  • 感恩天地滋养,宇宙永恒;感恩大自然无私的爱;感恩祖先传承、历代宗亲护佑;感恩国泰民安、繁荣昌盛;感恩父母生养大恩、...
    天门金珠瑜伽阅读 219评论 1 1
  • 文 | 戴文子 最近在读什么书? 《单程票》。 这是一本让你读完之后忍不住想爆粗的小说。 你的智商被玩弄戏耍于股掌...
    戴文子阅读 769评论 0 5