Java —— Leetcode Easy problem #1 (1-20 )

After learning the basics of Java, I started solving some easy questions on LeetCode in Java. Now I plan to practice a few questions every day and this will be my notes of solving problems. (190716)

1. 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.

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

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

Solution:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<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 k = target - nums[i];
            if(map.containsKey(k) && map.get(k)!=i){
                return new int[] {i,map.get(k)};
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

Use the hashmap can solve it easily.

7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

//Example 1:
Input: 123
Output: 321

//Example 2:
Input: -123
Output: -321

//Example 3:
Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution

class Solution {
    public int reverse(int x) {
        long res = 0;
        while(x!=0){
            int k = x % 10;
            res = res*10 + k;
            x /= 10;
        }
        if(res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) {
            return 0;
        } else {
            return (int) res;
        }
    }
}

we can use “long” to solve the overflows. Compared with the official answer, it looks less complicated.

9. 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?

My Solution:

class Solution {
    public boolean isPalindrome(int x) {
        String k = String.valueOf(x);
        String res = "";
        for(int i = 0; i < k.length(); i++) {
            res = k.charAt(i) + res;
        }
        if(res.equals(k)) {
            return true;
        } else {
            return false;
        }
    }
}

It’s easy problem and that’s my initial solution. It can solve the problem but it’s not so good.

Other Solution :

public boolean isPalindrome(int x) {
    String str = String.valueOf(x);
    int start = 0;
    int end = str.length() - 1;
    while(start < end){
        if(str.charAt(start++) != str.charAt(end--)) return false;
    }
    return true;
}

That’s the solution I found in the comments and I think it’s a better one.

Follow up Solution:

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

That’s faster and smaller solution than those two above.

13. 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.

My solution:

class Solution {
    public int romanToInt(String s) {
        HashMap<String, Integer> map = new HashMap<> ();
		String[] a = {"I","V","X","L","C","D","M"};
		Integer[] b = {1, 5, 10, 50, 100, 500, 1000};
		for(int i = 0; i < a.length; i++) {
			map.put(a[i], b[i]);
		}
		int res = map.get(s.charAt(s.length()-1)+"");
		int c = 0;
		for(int i =s.length()-1; i > 0; i--) {
			c = map.get(s.charAt(i)+"");
			if(map.get(s.charAt(i-1)+"") < c ) {
				c = map.get(s.charAt(i-1)+"");
				res -= c;
			} else {
				c = map.get(s.charAt(i-1)+"");
				res += c;
			}	
		}
		return res;
    }
}

Other Solution:

public int romanToInt(String s) {
	int ret=0;
	int[] number=new int[s.length()+1];
	for(int i=0;i<s.length();i++){
		if(s.charAt(i)=='M'){
			number[i]=1000;
		}else if(s.charAt(i)=='D'){
			number[i]=500;
		}else if(s.charAt(i)=='C'){
			number[i]=100;
		}else if(s.charAt(i)=='L'){
			number[i]=50;
		}else if(s.charAt(i)=='X'){
			number[i]=10;
		}else if(s.charAt(i)=='V'){
			number[i]=5;
		}else if(s.charAt(i)=='I'){
			number[i]=1;
		}
	}
	for(int i=0;i<s.length();i++){
    	if(number[i]>number[i+1]){
    		ret=ret+number[i];
    	}else if(number[i]<number[i+1]){
    		ret=ret+number[i+1]-number[i];
    		i++;
    	}else if(number[i]==number[i+1]){
    		ret=ret+number[i];
    	}else if(number[i]==1){
    		ret=ret+number[i];
    	}
    }
    return ret;
}

This solution is faster which only needs 3ms. (my solution needs 10ms)

14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:
All given inputs are in lowercase letters a-z.

My Solution:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        String res = "";
        if(strs.length != 0) {   
            for(int i = 0; i < strs[0].length(); i++) {
                String ele = strs[0].substring(i, i+1);
                for(int a = 1; a < strs.length; a++) {
                    if(i < strs[a].length()) {
                        if(!ele.equals(strs[a].substring(i,i+1)) ) {
                            return res;
                        }
                    } else {
                        return res;
                    }
                }
                res += ele;
            }
        }
        return res;
    }
}

Runtime: 1 ms, faster than 73.95% of Java online submissions for Longest Common Prefix.
Memory Usage: 36.3 MB, less than 99.71% of Java online submissions for Longest Common Prefix.

At begin I made a big mistake that I forgot to add the condition used to judge whether the input was empty. So there were always java.lang.ArrayIndexOutOfBoundsException: 0.

Official Solution:

public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    String prefix = strs[0];
    for (int i = 1; i < strs.length; i++)
        while (strs[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.isEmpty()) return "";
        }        
    return prefix;
}
public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) return "";
    for (int i = 0; i < strs[0].length() ; i++){
        char c = strs[0].charAt(i);
        for (int j = 1; j < strs.length; j ++) {
            if (i == strs[j].length() || strs[j].charAt(i) != c)
                return strs[0].substring(0, i);             
        }
    }
    return strs[0];
}

The first solution is really cool and the second one is simplified version of mine.

20. Valid Parentheses

Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

My Solution
At first I tried to solve it by myself but I failed … After view some comments I got a great idea from a dude who written in Python. Below it’s his idea and I just transfer it to Java.

class Solution {
    public boolean isValid(String s) {
        while(s.contains("()") || s.contains("[]") || s.contains("{}")) {
            s = s.replace("()","");
            s = s.replace("[]","");
            s = s.replace("{}","");
        }
        return s.equals("");
    }
}

Runtime: 81 ms, faster than 5.04% of Java online submissions for Valid Parentheses.
Memory Usage: 37.7 MB, less than 5.09% of Java online submissions for Valid Parentheses.

Though it’s time cosumed but I still think it’s a really good idea.

Official Solution

class Solution {

  // Hash table that takes care of the mappings.
  private HashMap<Character, Character> mappings;

  // Initialize hash map with mappings. This simply makes the code easier to read.
  public Solution() {
    this.mappings = new HashMap<Character, Character>();
    this.mappings.put(')', '(');
    this.mappings.put('}', '{');
    this.mappings.put(']', '[');
  }

  public boolean isValid(String s) {

    // Initialize a stack to be used in the algorithm.
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      // If the current character is a closing bracket.
      if (this.mappings.containsKey(c)) {

        // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
        char topElement = stack.empty() ? '#' : stack.pop();

        // If the mapping for this bracket doesn't match the stack's top element, return false.
        if (topElement != this.mappings.get(c)) {
          return false;
        }
      } else {
        // If it was an opening bracket, push to the stack.
        stack.push(c);
      }
    }

    // If the stack still contains elements, then it is an invalid expression.
    return stack.isEmpty();
  }
}

The official solution also use the method of removing same type parentheses from inside to outside. But it uses stack which I’m not familiar with. If you were interested in it, you could go to the website below to view some details of those algorithm.
https://leetcode.com/problems/valid-parentheses/solution/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
项目:使用 JavaScript 编写的杀死幽灵游戏(附源代码) 杀死鬼魂游戏是使用 Vanilla JavaScript、CSS 和 HTML 画布开发的简单项目。这款游戏很有趣。玩家必须触摸/杀死游荡的鬼魂才能得分。您必须将鼠标悬停在鬼魂上 - 尽量得分。鬼魂在眨眼间不断从一个地方移动到另一个地方。您必须在 1 分钟内尽可能多地杀死鬼魂。 游戏制作 这个游戏项目只是用 HTML 画布、CSS 和 JavaScript 编写的。说到这个游戏的特点,用户必须触摸/杀死游荡的幽灵才能得分。游戏会根据你杀死的幽灵数量来记录你的总分。你必须将鼠标悬停在幽灵上——尽量得分。你必须在 1 分钟内尽可能多地杀死幽灵。游戏还会显示最高排名分数,如果你成功击败它,该分数会在游戏结束屏幕上更新。 该游戏包含大量的 javascript 以确保游戏正常运行。 如何运行该项目? 要运行此游戏,您不需要任何类型的本地服务器,但需要浏览器。我们建议您使用现代浏览器,如 Google Chrome 和 Mozilla Firefox。要玩游戏,首先,单击 index.html 文件在浏览器中打开游戏。 演示: 该项目为国外大神项目,可以作为毕业设计的项目,也可以作为大作业项目,不用担心代码重复,设计重复等,如果需要对项目进行修改,需要具备一定基础知识。 注意:如果装有360等杀毒软件,可能会出现误报的情况,源码本身并无病毒,使用源码时可以关闭360,或者添加信任。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值