java算法篇给定一个数组找出第一个重复(不重复)的元素
发布日期:2021-06-30 16:19:31 浏览次数:2 分类:技术文章

本文共 2758 字,大约阅读时间需要 9 分钟。

第一个重复算法分析(倒序放入map,最后一个重复的元素)

第一个想到的是用hashmap存储元素,计算出现次数,然后遍历hashmap,输入值为1的元素。

但是后来发现不对,输出的是所有出现一次的元素,因为map是无序的,不一定是第一个。怎么办?

在遍历数组,存入hashmap的时候,判断如果不存在,就设置index=i,记录索引。但是此时map没有内容,根本无法判断是否重复?怎么办?倒序遍历数组就可以满足。

  • 倒序遍历数组,放入map
  • 如果map存在,value为出现次数,加1
  • 如果map不存在,index=i,记录当前元素位置。
  • 最后index的值就是第一个不重复的元素位置

代码

package com.puhui.goosecard.web;import java.util.HashMap;import java.util.Map;/** * 2 * @Author: kerry * 3 * @Date: 2018/9/14 14:07 * 4 */public class Test {    public static void main(String[] args) {        char[] array = {'d', 'a', 'b', 'c', 'c', 'b'};        Map
map = new HashMap<>(); int index = -1; for (int i = array.length - 1; i >= 0; i--) { if (map.containsKey(array[i])) { int count = (Integer) map.get(array[i]); map.put(array[i], count + 1); index = i; } else { map.put(array[i], 1); } } System.out.println(index); }}

第一个不重复算法分析(次数为1,索引最小)

类比重复的算法思路,其实是错误的:

char[] array = {'a', 'b', 'b', 'b', 'c', 'c', 'e', 'a'};

当循环到b的时候,不重复,index指向索引为3 的位置。继续循环,还是b,重复,index不变化,直到第一个元素也不变化,所以最后输出的四3.但是不是正确的结果。

  • 遍历,hash存储元素出现次数和元素索引,为了下一步比较索引最小
  • 输出元素出现次数为1的并且索引最小

代码

package com.puhui.goosecard.web;import java.util.HashMap;import java.util.Map;/** * 2 * @Author: kerry * 3 * @Date: 2018/9/14 14:07 * 4 */public class Test {    private static class CountIndex {        int count;        int index;        public int getCount() {            return count;        }        public void setCount(int count) {            this.count = count;        }        public int getIndex() {            return index;        }        public void setIndex(int index) {            this.index = index;        }    }    public static void main(String[] args) {        char[] array = {'a', 'd', 'e', 'b', 'c', 'c', 'b'};        Map
map = new HashMap<>(); int result = Integer.MAX_VALUE; for (int i = 0; i < array.length; i++) { if (!map.containsKey(array[i])) { CountIndex countIndex = new CountIndex(); countIndex.setCount(1); countIndex.setIndex(i); map.put(array[i], countIndex); } else { CountIndex countIndex = map.get(array[i]); countIndex.setCount(countIndex.getCount() + 1); map.put(array[i], countIndex); } } for (int i = 0; i < array.length; i++) { // If this character occurs only once and appears // before the current result, then update the result if (map.get(array[i]).count == 1 && result > map.get(array[i]).index) { result = map.get(array[i]).index; } } System.out.println(result); }}

 

 

 

转载地址:https://kerry.blog.csdn.net/article/details/82703535 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java框架篇spring sleuth分布式日志查询
下一篇:Java架构篇rest api 幂等性

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月08日 09时37分15秒