标签:cat contains class ber exception two sum reverse mat 两数之和
1.两数之和
1 class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 Map<Integer, Integer> map = new HashMap<>(); 4 for(int i = 0; i<nums.length;i++){ 5 int tmp = target - nums[i]; 6 if(map.containsKey(tmp)){ 7 return new int[]{map.get(tmp),i}; //存在即返回 8 } 9 map.put(nums[i],i); //不存在,则加入 10 } 11 throw new IllegalArgumentException("No two sum solution"); 12 } 13 }
总结:熟悉了HashMap的使用
2.
1 class Solution { 2 public int reverse(int x) { 3 try{ 4 if(x>0){ 5 StringBuilder str = new StringBuilder().append(x); 6 return Integer.parseInt(str.reverse().toString()); 7 }else{ 8 StringBuilder str = new StringBuilder().append(-x); 9 return Integer.parseInt(str.reverse().toString())*(-1); 10 } 11 }catch(NumberFormatException e){ 12 return 0; 13 14 } 15 } 16 }
总结:为了好的扩展性,使用StringBuilder来创建,之后用到了str.reverse()方法和此处Integer.parseInt(str.reverse().toString())的妙用,以及对于负数的机智处理
标签:cat contains class ber exception two sum reverse mat 两数之和
原文地址:https://www.cnblogs.com/Elliott666/p/11517512.html