zoukankan      html  css  js  c++  java
  • single-number-ii

    /**

    *
    * @author gentleKay
    * Given an array of integers, every element appears three times except for one. Find that single one.
    * Note:
    * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
    *
    * 给定一个整数数组,除一个元素外,每个元素都出现三次。找到那个。
    * 注:
    * 您的算法应该具有线性运行时复杂性。你能在不使用额外内存的情况下实现它吗?
    */

    获取map集合中键和值的三种方式:

    https://www.cnblogs.com/strive-19970713/p/11282676.html

    import java.util.*;
    
    /**
     * 
     * @author gentleKay
     * Given an array of integers, every element appears three times except for one. Find that single one.
     * Note: 
     * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
     * 
     * 给定一个整数数组,除一个元素外,每个元素都出现三次。找到那个。
     * 注:
     * 您的算法应该具有线性运行时复杂性。你能在不使用额外内存的情况下实现它吗?
     */
    
    public class Main27 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		int[] A = {3,3,3, 5,5,5, 6,6,6,7,7,8,7};
    		System.out.println(Main27.singleNumber(A));
    	}
    
    	public static int singleNumber(int[] A) {
    		
    		Map<Integer, Object> map = new HashMap<>();
    		
    		for (int i=0;i<A.length;i++) {
    			if (map.containsKey(A[i])) {
    				map.put(A[i], 2); //一旦有map里面重复这个key, 就将它的值改成 2 或者其他值。
    			}else {
    				map.put(A[i], 1); //没有包含这个key键的话, 就将这个键的值为1。
    			}
    		}
    		//方法一
    //		Set<Integer> set = map.keySet();
    //		Iterator<Integer> it = set.iterator();
    //		while (it.hasNext()) {
    //			Integer key = (Integer)it.next();
    //			Integer value = (Integer)map.get(key);
    //			if (value == 1) {
    //				return key;
    //			}
    //		}
    		//方法二
    //         Set<Integer> set = map.keySet(); // for (Integer i : set) { // Integer value = (Integer) map.get(i); // if (value == 1) { // return i; // } // } //方法三 Set<Map.Entry<Integer, Object>> set = map.entrySet(); for (Map.Entry<Integer, Object> m : set) { if ((Integer)m.getValue() == 1) { return m.getKey(); } } return 0; } }

      

  • 相关阅读:
    shell脚本编程练习
    linux中()、[]、{}、(())、[[]]等各种括号的使用
    Linux Shell 变量自加
    while read line [linux] shell 学习
    踢出某正在访问的用户||永久禁止某IP访问
    linux设置 自定义脚本开机启动
    syntax error: unexpected end of file完美解决方案
    Linux利用nc命令脚本批量检测服务器指定端口是否开放
    41-贪心算法
    38-动态规划
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11282727.html
Copyright © 2011-2022 走看看