[Leetcode][第657题][JAVA][机器人能否返回原点][数组][HashMap]
【問(wèn)題描述】[簡(jiǎn)單]
【解答思路】
遍歷方向 看是否回到原點(diǎn) 或者 “上下” “左右”兩個(gè)方向的數(shù)量是否相等
1. 方向
時(shí)間復(fù)雜度:O(N) 空間復(fù)雜度: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 i=0;i<moves.length();i++){char c=a[i];if(c=='U')x+=1;if(c=='D')x-=1;if(c=='L')y-=1;if(c=='R')y+=1;}return x==0&&y==0;} }2. 數(shù)組
時(shí)間復(fù)雜度:O(N) 空間復(fù)雜度: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
時(shí)間復(fù)雜度:O(N) 空間復(fù)雜度:O(1)
class Solution {public boolean judgeCircle(String moves) {HashMap<Character,Integer> map = new HashMap<Character,Integer>(); //一定要先放入 不最后判斷可能找不到 因?yàn)?可能沒(méi)有某個(gè)方向 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 ;i<len;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')));} }【總結(jié)】
1. 反思
沒(méi)有想清楚就開(kāi)始動(dòng)手 簡(jiǎn)單題!!!硬是搞了半天!!!
輸出最后的判斷不一定要遍歷 要學(xué)會(huì)思考特判
2.hashmap最后判斷equals
值得注意的是最后判斷要用.equals不能用==。
Integer是int的包裝類,雖然能自動(dòng)拆箱,但是Integer本質(zhì)上是一個(gè)對(duì)象,我們==比較的是堆中的地址。
我們看一下jdk中Integer的源碼
默認(rèn)IntegerCache.low = -127, IntegerCache.high = 128, 所以在這個(gè)范圍內(nèi)比較的是值,如果不在這個(gè)范圍內(nèi)他回去new一個(gè)新的Integer對(duì)象,這時(shí)候比的就是地址了。
參考鏈接: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/
總結(jié)
以上是生活随笔為你收集整理的[Leetcode][第657题][JAVA][机器人能否返回原点][数组][HashMap]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【MVC】AJAX+PartialVie
- 下一篇: html中车牌号省份简称输入键盘