LeetCode 答案(Easy)(1-100)

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.
你需要确保每个输入的数组都有一个确定的解,并且每个元素只能使用一次。

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
  • 答案
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0, length = nums.length; i < length; i++) {

            for (int j = i + 1; j < length; j++) {

                if (nums[i] + nums[j] == target) {
                    int[] newNum = { i, j };
                     //System.out.println("["+i+","+j+"]");
                    return newNum;
                }
            }
        }
        return null;
    }
}


7-Reverse Integer(逆置整数)

Reverse digits of an integer.
逆置一个整数
Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

  • 答案
public class Solution {
    public int reverse(int x) {
        String start = x + "";
        char[] arr = start.toCharArray();
        StringBuffer sb = new StringBuffer();
        if (x >= 0) {
            for (int length = arr.length, i = length - 1; i >= 0; i--) {
                sb.append(arr[i]);
            }
            try {
                return Integer.parseInt(sb.toString());
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                return 0;
            }
        } else {
            for (int length = arr.length, i = length - 1; i > 0; i--) {
                sb.append(arr[i]);
            }
            try {
                return Integer.parseInt("-" + sb.toString());
            } catch (NumberFormatException e) {
                return 0;
            }
        }


    }
}


9-Palindrome Number(回文数字)

Determine whether an integer is a palindrome. Do this without extra space.
确认一个整数是否是回文数。不要使用额外的存储空间
click to show spoilers.

Some hints:
Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

  • 答案
public class Solution {
    public boolean isPalindrome(int x) {
        String xString = x + "";
        int count = 0, length = xString.length(), middle = length / 2;
        for (int i = 0; i < middle; i++) {
            if (xString.charAt(i) == xString.charAt(length - 1 - i)) {
                count++;
            }
        }
        if (count == middle) {
            return true;
        } else {
            return false;
        }

    }
}


13-Roman to Integer (罗马数转阿拉伯数)

Given a roman numeral, convert it to an integer.
输入一个罗马数,转换成阿拉伯数

Input is guaranteed to be within the range from 1 to 3999.
输入的范围是1-3999

  • 答案
public class Solution {
    public int romanToInt(String s) {
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        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);

        int sum = map.get(s.charAt(0)), length = s.length();
        for (int i = 1; i < length; i++) {

            if (map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) {
                sum = sum + map.get(s.charAt(i)) - 2 * map.get(s.charAt(i - 1));

            } else {
                sum += map.get(s.charAt(i));
            }

        }

        return sum;




    }
}


20-Valid Parentheses (有效的括号字符串)

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
给定一个字符串,只包括’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 以及 ‘]’这些字符,确认它是否有效。

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
括号必须要正确的关闭,”()” 和”()[]{}”是有效的,但是 “(]” 和”([)]” 无效
- 答案

public class Solution {
    public boolean isValid(String s) {
        boolean result= false;  
        //while循环的次数
        int countwhile =0;
        //匹配到的对的数量
        int num=0;
        //输入的字符串的长度
        int paramLenth =s.length();
        while(countwhile<paramLenth){
            char[] chs = s.toCharArray();
            w: for(int i=1,length=chs.length;i<length;i++){
                String str=s.charAt(i-1)+""+s.charAt(i);
                if(str.equals("{}")||str.equals("()")||str.equals("[]")){
                    num ++;
                    s=s.substring(0, i-1)+s.substring(i+1, s.length());
                    break w;

                }
            }
            countwhile++;

        }
        if(num==paramLenth/2&&paramLenth%2==0){
            result= true;
        }
        return result;
    }
}


28-Implement strStr() [ 实现strStr() 即indexOf()]

Implement strStr().
实现strStr() 即indexOf()

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
返回needle第一次出现在haystack时的索引,如果不存在就返回 -1

  • 答案
public class Solution {
    public int strStr(String haystack, String needle) {

        int needleLength=needle.length();
        int haystackLength = haystack.length();
        int result=-1;
        if("".equals(needle)){
            return 0;
        }
        for (int i =needleLength-1 ; i < haystackLength; i++) {
            String moveableString=haystack.substring(i+1-needleLength, i+1);
            if(moveableString.equals(needle)){
                result=i+1-needleLength;
                break;
            }
        }
        return result;

    }
}


35-Search Insert Position (查找插入位置)

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
给定一个已经排好序的数组(升序) 以及一个目标值,返回目标值在数组中的位置,如果不存在,那么就返回目标值应该放在的未知的索引

You may assume no duplicates in the array.
数组中没有重复元素

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

  • 答案
public class Solution {
    public int searchInsert(int[] nums, int target) {


        int length = nums.length;
        int start = 0;
        int end = length - 1;

        while (start <= end) {
            // System.out.println(start+"----"+end);
            int middle = (start + end) / 2;
            if (nums[middle] > target) {
                end = middle - 1;

            } else if (nums[middle] < target) {
                start = middle + 1;
            } else {
                return middle;
            }
        }
        return start;



    }
}


53-Maximum Subarray (最大的子数组)

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
截取数组,找出和最大的子数组。元素要相邻且至少有一个元素。

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
例如:给定的数组 [-2,1,-3,4,-1,2,1,-5,4],
相邻的子数组 [4,-1,2,1] 有一个最大的和 6

click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

  • 答案
//典型的动态规划问题:
//思路:
//首先,很显然在连续累加的过程中,加了nums[i]如果sum是小于0的,那么说明前一次计算出的sums其副作用,  需要重新寻找起始开始累加
//即重新以当前nums[i]为起始值开始累加
public class Solution {
    public int maxSubArray(int[] nums) {

    int maxSum = nums[0];//记录累加过程中的最大值
    int subSum = nums[0];
    for(int i = 1; i < nums.length; i++)
    {
        subSum = subSum <= 0? nums[i] : subSum+nums[i];
        if(subSum > maxSum) 
            maxSum = subSum;
    }
    return maxSum;


    }
}


58-Length of Last Word(最后一个单词的长度)

Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.
给定一个由大小写字母以及空格构成的句子,返回句子中最后一个单词的长度

If the last word does not exist, return 0.
如果不存在最后一个单词 ,返回0

Note: A word is defined as a character sequence consists of non-space characters only.

For example,
Given s = “Hello World”,
return 5.

  • 答案
class Solution {
    public int lengthOfLastWord(String s) {
        //按" "将字符串分成单词的数组
        String[] words=s.trim().split(" ");
        //返回数组中最后一个单词的长度
        return words[words.length-1].length();

    }
}


69-Sqrt(x) 求平方根

Implement int sqrt(int x).
实现 int sqrt(int x)

Compute and return the square root of x.
计算并返回x的平方根

  • 答案
public class Solution {
    public int mySqrt(int x) {




        double start = 0, end = x;
        double middle = 1;
        double result = 1;

        while (Math.abs(x - result) > 0.000001) {
            middle = (start + end) / 2;
            result = middle * middle;

            if (result <= x) {
                start = middle;

            } else {
                end = middle;

            }

        }
        //System.out.println(middle);
        return (int) middle;





    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值