LeetCode刷题日记(1)—Easy*4

欢迎浏览我的博客 获得更多精彩文章
https://boyn.top

LeetCode刷题日记(1)—Easy*4

今天下午刷了4道Easy的题

题目 链接 所用时间 语言
Two Sum Accepted 2 ms java
Two Sum II - Input array is sorted Accepted 0 ms java
Palindrome Number Accepted 6 ms java
Roman to Integer Accepted 13 ms java

Two Sum

问题描述

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

问题思路

这道题是leetcode的第一题,基本没有什么好说的,我的解法是用键值对,遍历输入数组,每个循环会运算一次map中有没有值是target-nums[i]时,有的话说明这个值就是我们要找的值,把他组成数组并输出,没有的话就先把这个值放到map中

值得注意的是,map.containsKey(int value)这个方法是通过值找键,由于是计算hash值来寻找的,并没有想象中得慢

然后处理一些边界条件,就结束了.

Code

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length<2||nums==null) return new int[]{0,0};
        Map<Integer,Integer> map = new HashMap<>();
        for(int i= 0;i<nums.length;i++){
            if(map.containsKey(target-nums[i])){
                return new int[]{map.get(target-nums[i]),i};
            }
            map.put(nums[i],i);
        }
        return new int[]{0,0};
    }
}

Two Sum II - Input array is sorted

问题描述

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

问题思路

这题是上一题的变种,不同的就是所给的数组是有序的,从小到大排列,所以就可以使用不同的思路了.

我在这先确定了两个指针 指向输入数组的起点和终点,即最小和最大

然后开始循环,循环维持条件为左指针小于右值针

每次循环时,都计算一次数值,当数值比目标大,将右值针左移使结果变小

当数值比目标小,将左指针右移使结果变大

当两者相等时返回结果.

Code

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length<2||nums==null) return null;
        int left=0;
        int right = nums.length-1;
        while(left<right){
            int result = nums[left]+nums[right];
            if(result>target) right--;
            else if(result <target) left++;
            else{
                return new int[]{left+1,right+1};
            }
        }
        return null;
    }
}

Palindrome Number

问题描述

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

问题思路

在第一次时,用了一个比较绕的思路,先取得这个数的位数,然后根据位数用除法和取余一位一位地验证,这样的后果就是虽然速度并不差,但是代码量却变大了而且也比较复杂.

在第二次时,观看了dalao的代码后,醍醐灌顶,只需要把这个数反转过来,再与原数比较,不就可以了吗?

Code

第一次

class Solution {
    public final  static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
    public final  static int [] bitTable = {0,1,10, 100, 1000, 10000, 100000, 1000000, 10000000,100000000, 1000000000};
    public boolean isPalindrome(int x) {
        
        if(x<0) return false;
        else if(x<10) return true;
        else{
            int bigPtr = stringSize(x);
            int smallPtr = 1;
            while(bigPtr>smallPtr){
                int big = x/bitTable[bigPtr--]%10;
                int small = x%bitTable[smallPtr+1]/bitTable[smallPtr];
                smallPtr++;
                if(big!=small) return false;
            }
        }
        return true;
    }
    
    

    public  static int stringSize(int x) {
    for (int i=0; ; i++)
        if (x <= sizeTable[i])
            return i+1;
}
}

第二次

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0) return false;
        else if(x<10) return true;
        else{
        int temp = x;
        int reverse = 0;
        while(temp!=0){
            reverse  =reverse*10 + (temp%10);
            temp/=10;
        }
        return x==reverse;
        }
    }
    
}

Roman to Integer

问题描述

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

Example 3:

Input: "IX"
Output: 9

Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

问题思路

这题是将罗马数字转换成阿拉伯数字,难点就在于罗马数字的表示方法与阿拉伯数字并不相同,如果一个数的右边是一个比他位数多一位的数时,那么就表示的是(右边-左边),知道了这个规则,就可以比较简单地做出来了:

先将符号和对应的值用键值对连接起来,然后开始读入值,这里用一个栈来管理这些值,其中规则如下:

1.当栈为空时,直接将读入值压栈

2.若栈非空,将栈顶的值跟读入值比较

2.1 若栈顶值较大,那么将读入值压栈

2.2 若读入值较大,那么将栈顶值出栈,并作运算:结果+=读入值-栈顶值

最后,将还在栈中的值一一出栈并加起来即可

Code

import java.util.*;

class Solution {

    public int romanToInt(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        int result = 0;
        Map<Character, Integer> roman = new HashMap<>();
        roman.put('I', 1);
        roman.put('V', 5);
        roman.put('X', 10);
        roman.put('L', 50);
        roman.put('C', 100);
        roman.put('D', 500);
        roman.put('M', 1000);
        Stack<Integer> symbol = new Stack<>();
        int valueCompare;
        char ch;
        for (int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);
            int out = roman.get(ch);
            if (symbol.empty()) {
                symbol.push(out);
                continue;
            } else {
                valueCompare = symbol.peek();
                if (valueCompare < out) {
                    result += out - valueCompare;
                    symbol.pop();
                } else {
                    symbol.push(out);
                }

            }
            
        }
        while (!symbol.empty()) {
                result += symbol.pop();
            }

        return result;
    }
}

你可能感兴趣的:(算法,Java,leetcode)