[Data structure] Hash table: LeetCode question (2) 1. Sum of two numbers, 13. Roman numerals to integers

1. The sum of two numbers¹

Given an array of integers numsand a target value target, and you find that the target value in the array of two integers, and return to their array subscript.

You can assume that each input will only correspond to one answer. However, you cannot reuse the same elements in this array.

Example:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

1. Solution 1: Enumeration

  • Idea: nothing to say, just enumerate all the results
  • the complexity
    • Time:O(n^2),66ms
    • Space:O(1)
public int[] twoSum(int[] nums, int target) {
    
    
        for (int i = 0; i < nums.length - 1; i++) {
    
    
            for (int j = i + 1; j < nums.length; j++) {
    
    
                if (nums[i] + nums[j] == target) 
                    return new int[]{
    
    i,j};
            }
        }
        return new int[0];
}

2. Solution 2: HashMap

  • Idea: In order to reduce the complexity to O(n), the idea of ​​changing space for time can be adopted, that is, to introduce a container. What is appropriate to introduce? List? Set? Map? Because the index is to be returned, a KV relationship is actually included here, so a HashMap can be used, where the key is the value, and the value is the array index.
  • the complexity
    • Time:O(n),2ms
    • Space: O(n), a Map is needed to save the elements in the array
public int[] twoSum(int[] nums, int target) {
    
    
       HashMap<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) 
        	// 如果map有与当前值匹配的,就直接取出索引返回,否则将当前值和索引加入map
            if (map.containsKey(target - nums[i])) 
                return new int[]{
    
    map.get(target - nums[i]),i};
            else 
                map.put(nums[i],i);
        return null;
}

13. Roman Numerals to Integers¹

Roman numerals contains the following seven Icharacters: V, X, L, C, , Dand M.

字符          数值
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, the Roman numeral 2 is written IIas two parallel ones . 12 is written XIIas X+ II. 27 is written XXVIIas XX+ V+ II.

Normally, the small numbers in Roman numerals are to the right of the large numbers. But there are special cases, for example, 4 is not written IIII, but instead IV. The number 1 is to the left of the number 5, and the number represented is equal to the number 4 obtained by subtracting the number 1 from the large number 5. Similarly, the number 9 is expressed as IX. This special rule only applies to the following six situations:

  • ICan be placed to the left of V(5) and X(10) to represent 4 and 9.
  • XIt can be placed to the left of L(50) and C(100) to represent 40 and 90.
  • CIt can be placed to the left of D(500) and M(1000) to represent 400 and 900.

Given a Roman numeral, convert it to an integer. Ensure that the input is in the range of 1 to 3999.

Example 1:

输入: "III"
输出: 3

Example 2:

输入: "IV"
输出: 4

Example 3:

输入: "IX"
输出: 9

Example 4:

输入: "LVIII"
输出: 58
解释: L = 50, V= 5, III = 3.

Example 5:

输入: "MCMXCIV"
输出: 1994
解释: M = 1000, CM = 900, XC = 90, IV = 4.

prompt:

  • The test cases given in the question all comply with the Roman numeral writing rules, and there will be no cross-bits and other situations.
  • Examples such as IC and IM do not meet the requirements of the title. 49 should be written as XLIX, and 999 should be written as CMXCIX.
  • On detailed rules for writing Roman numerals, you can refer to the Roman numeral - Mathematics .

Solution: HashMap

  • Ideas
    1. You can think of the KV relationship at a glance in this question, and the key is an unrelated character, so HahsMap can be used here. At the same time, the core problem has become the handling of IV, IX, XL, XC, CD, and CM.
    2. Looking for a pattern, I found that the overall IV will be 2 smaller than I+V, IX will be 2 smaller than I+X, XL will be 20 smaller than X+L, XC will be 20 smaller than X+C, and CD will be 200 smaller than C+D. CM will be 200 smaller than C+M.
    3. So you can first subtract these 2,20,200 from the result, and then add them one by one
  • the complexity
    • Time: O(n), positively related to the length of the string
    • Space: O(1), there are only 8 Roman characters, so the size of HashMap is determined
class Solution {
    
    
    Map<Character, Integer> map = new HashMap<>(){
    
     
        // 在构造时进行初始化,{put}
        {
    
    
            put('I', 1);
            put('V', 5);
            put('X', 10);
            put('L', 50);
            put('C', 100);
            put('D', 500);
            put('M', 1000);
        }
    }; // 这里注意别忘记 ;
    

    public int romanToInt(String s) {
    
    
        int sum = 0;
		
        // 通过indexOf判断是否存在特殊,然后减去相应值
        if(s.indexOf("IV")!=-1){
    
    sum-=2;}
        if(s.indexOf("IX")!=-1){
    
    sum-=2;}
        if(s.indexOf("XL")!=-1){
    
    sum-=20;}
        if(s.indexOf("XC")!=-1){
    
    sum-=20;}
        if(s.indexOf("CD")!=-1){
    
    sum-=200;}
        if(s.indexOf("CM")!=-1){
    
    sum-=200;}
        
        // 遍历所有字符,累加即可
        for (char c : s.toCharArray()) {
    
    
            sum += map.get(c);
        }

        return sum;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43935927/article/details/114109692