移动网站如何做权重,南通企业建站模板,大连开发区图书馆,南京华夏天成建设有限公司网站【问题描述】[简单] 【解答思路】
遍历方向 看是否回到原点 或者 “上下” “左右”两个方向的数量是否相等
1. 方向
时间复杂度#xff1a;O(N) 空间复杂度#xff1a;O(1)
class Solution {public boolean judgeCircle(String moves) {int x 0,y 0;int len moves.len…【问题描述】[简单] 【解答思路】
遍历方向 看是否回到原点 或者 “上下” “左右”两个方向的数量是否相等
1. 方向
时间复杂度O(N) 空间复杂度O(1)
class Solution {public boolean judgeCircle(String moves) {int x 0,y 0;int len moves.length();if(len 0){return true;}if(len%2!0){return false;}char[] a moves.toCharArray();for(int i0;imoves.length();i){char ca[i];if(cU)x1;if(cD)x-1;if(cL)y-1;if(cR)y1;}return x0y0;}
}2. 数组
时间复杂度O(N) 空间复杂度O(N)
class Solution {public boolean judgeCircle(String moves) {int[] res new int[26];int len moves.length();if(len 0){return true;}if(len%2!0){return false;}char[] c moves.toCharArray();for(char ch :c){res[ch-A];}return res[U-A]res[D-A]res[L-A]res[R-A];}
}3. HashMap
时间复杂度O(N) 空间复杂度O(1)
class Solution {public boolean judgeCircle(String moves) {HashMapCharacter,Integer map new HashMapCharacter,Integer(); //一定要先放入 不最后判断可能找不到 因为 可能没有某个方向 map.put(U, 0);map.put(D, 0);map.put(L, 0);map.put(R, 0);int len moves.length();if(len 0){return true;}if(len%2!0){return false;}char[] c moves.toCharArray();for(int i 0 ;ilen;i ){if(map.containsKey(c[i])){map.put(c[i],map.get(c[i])1);}}return (map.get(U).equals(map.get(D)))(map.get(L).equals(map.get(R)));}
}【总结】
1. 反思
没有想清楚就开始动手 简单题硬是搞了半天 输出最后的判断不一定要遍历 要学会思考特判
2.hashmap最后判断equals
值得注意的是最后判断要用.equals不能用。 Integer是int的包装类虽然能自动拆箱但是Integer本质上是一个对象我们比较的是堆中的地址。 我们看一下jdk中Integer的源码
public static Integer valueOf(int i) {if (i IntegerCache.low i IntegerCache.high)return IntegerCache.cache[i (-IntegerCache.low)];return new Integer(i);
}默认IntegerCache.low -127, IntegerCache.high 128, 所以在这个范围内比较的是值如果不在这个范围内他回去new一个新的Integer对象这时候比的就是地址了。
参考链接https://leetcode-cn.com/problems/robot-return-to-origin/solution/hen-rong-yi-li-jie-de-liang-chong-jie-ti-si-lu-by-/ 参考链接https://leetcode-cn.com/problems/robot-return-to-origin/solution/java-hashmap-by-jolyne-3/