Leetcode 第320场周赛

重回Leetcode,参与周赛学习一下。果然,Leetcode的比赛难度很真实,就是我连签到题都做不对,恩,这就对啦。

一共四道题,90分钟,好像比CSDN的短30分钟,做题可以不按照顺序。

签到题目是第一题,我的目标其实就是做出签到题,但是很遗憾,没有实现!

赛后去讨论区看了别人的题解,看到很多人用了hashmap,哎,数据结构啊,没有实现过,完全不能用起来。

找到了这个题解是java的,看起来很优秀,https://leetcode.cn/problems/number-of-unequal-triplets-in-array/solutions/1981751/by-longluo-kg4a/。

然而有我看不懂的地方 map.getOrDefault() 这个函数我在官方文档里没有找到啊。https://docs.oracle.com/javase/10/docs/api/java/util/HashMap.html 。
文档里只有map.get()。

基础不好到连别人的答案都看不都了,真是郁闷了。然而,不能灰心,一点一点补吧。

Hasmap补习一下

https://docs.oracle.com/javase/10/docs/api/java/util/HashMap.html

既然补习,就从官方文档开始。

Hashmap的数据类型是Object, 继承于AbstractMap,是一个用户存储映射键值对的数据结构。

官方文档里有:“All Implemented Interfaces:
Serializable, Cloneable, Map<K,V>”字样, 我的理解是方法方便实现了Serializable, Clonable和Map这几个接口类的全部方法,不知道对不对。

从这里查看Map这个结构类的方法,我就找到了map.getOrDefault()的函数定义了!还是要看官方文档啊!

Map.getOrDefault​(Object key, V defaultValue), 这个函数在找到key是返回key对应的Value,找不到key的时候返回defaultValue。

后面还有map.entrySet()的解释:“Set<Map.Entry<K,V>> entrySet()
Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.” 这里面说到的Set view是什么,就完全没有体会了。

恩,实践出真知,我们来实验一下吧,CSDN给我们的礼物有云容器和云IDE,用那个实验比较好呢?我很懒,就用云IDE吧

我们就用Leetcode官方给的测试用例1来实验,nums = [4,4,2,4,3]

我们在云IDE里面起一个默认模板代码的实例,因为默认就是java框架,是不是很方便?

然后我们找到src/main/DemoApplication.java。把它的main函数修改成下面的样子,注释掉最后一行运行demo的语句哦,否则不会输出我们想要看到的结果。


public static void main(String[] args) {

		int nums[] = {4 ,4, 2, 4, 3};

		Map<Integer, Integer> map = new HashMap<>();

        for (int x : nums) {
            map.put(x, map.getOrDefault(x, 0) + 1);
        }

		System.out.print( map);

		Set<Map.Entry<Integer, Integer>> entry = map.entrySet();
		
		

		System.out.print( entry);

		//SpringApplication.run(DemoApplication.class, args);

	}

输出 {2=1, 3=1, 4=3}[2=1, 3=1, 4=3],
所以map是{2=1, 3=1, 4=3},
而map的Set view是 [2=1, 3=1, 4=3]。

讲真我觉得有些意外,除了括号不一样,居然内容没有任何区别!

不过总归今天是实验了一下hashmap的内容,希望下次可以成功签到!

也非常感谢CSDN给的实验环境,对于我这样手残的人,这样的环境很重要。不枉我一如既往的购买CSDN的会员,希望CSDN能像Duolingo一样,保持不收费,但是超精彩。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不争之德

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值