本文共 1018 字,大约阅读时间需要 3 分钟。
LeetCode刷题:136. Single Number
原题链接:
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1 Example 2:Input: [4,1,2,1,2]
Output: 4算法设计
package com.bean.algorithm.basic;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.Map;public class SingleNumber { public static int singleNumber(int[] nums) { Mapmap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { Integer num = map.get(nums[i]); map.put(nums[i], num != null ? num + 1 : 1); } return Collections.min(map.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey(); } public static void main(String[] args) { // TODO Auto-generated method stub int[] arrays=new int[] {4,1,2,1,2}; int ANSWER = singleNumber(arrays); System.out.println("ANSWER = "+ANSWER); }}
程序运行结果:
ANSWER = 4
转载地址:http://yitdi.baihongyu.com/