1.两数之和——hashtable
/*class Solution { public int[] twoSum(int[] nums, int target) { for (int i=0;i<=nums.length;i++){ for (int j=i+1;j<=nums.length;j++){ if (nums[i]+nums[j]==target) { return new int[]{i,j}; } } } throw new IllegalArgumentException("No two sum solution"); } } */ class Solution { public int[] twoSum(int[] nums, int target){ Map<Integer, Integer>map = new HashMap<>(); for(int i=0; i<nums.length; i++){ map.put(nums[i],i); } for (int i=0; i <nums.length; i++){ int complement=target -nums[i]; if(map.containsKey(complement) && map.get(complement) != i){ return new int[] {i,map.get(complement)}; } } throw new IllegalArgumentException("No two sum solution") ; } }
2.罗马数字转整数
class Solution { public int romanToInt(String s) { Map<Character, Integer>map = new HashMap<>(); // 构造哈希表 map.put('I',1); map.put('V',5); map.put('X',10); map.put('L',50); map.put('C',100); map.put('D',500); map.put('M',1000); char c0 = s.charAt(s.length()-1); int n =map.get(c0); int m = 0; for(int i=0; i<s.length()-1; i++){ char c1 = s.charAt(i); char c2 = s.charAt(i+1); if(map.get(c1)>=map.get(c2)){ m = m + map.get(c1); } else { m =m-map.get(c1); } } return m+n; } } //耗时117ms,内存63.5MB