LintCode第三十四天

1104. Judge Route Circle

Initially, there is a Robot at position (0, 0). Given a sequence of
its moves, judge if this robot makes a circle, which means it moves
back to the original place finally.

The move sequence is represented by a string. And each move is
represent by a character. The valid robot moves are R (Right), L
(Left), U (Up) and D (down). The output should be true or false
representing whether the robot makes a circle.

样例
Example 1:

Input: “UD”
Output: true
Example 2:

Input: “LL”
Output: false

public class Solution {
    /**
     * @param moves: a sequence of its moves
     * @return: if this robot makes a circle
     */
    public boolean judgeCircle(String moves) {
        // Write your code here
        int flag=0;
        for(char c:moves.toCharArray()){
            if(c=='L'||c=='U')
                flag++;
            else flag--;
        }
        if(flag==0)
            return true;
        else return false;
    }
}

1112. Set Mismatch

The set S originally contains numbers from 1 to n. But unfortunately,
due to the data error, one of the numbers in the set got duplicated to
another number in the set, which results in repetition of one number
and loss of another number.

Given an array nums representing the data status of this set after the
error. Your task is to firstly find the number occurs twice and then
find the number that is missing. Return them in the form of an array.

样例
Input: nums = [1,2,2,4]
Output: [2,3]

public class Solution {
    /**
     * @param nums: an array
     * @return: the number occurs twice and the number that is missing
     */
    public int[] findErrorNums(int[] nums) {
        // Write your code here
        HashMap<Integer,Integer> map=new HashMap<>();
        int DouleRes=0;
        int sum=0;
        for(int i:nums){
            sum+=i;
            if(map.containsKey(i))
                DouleRes=i;
            else map.put(i,1);
        }
        int RealSum=0;
        for(int i=1;i<=nums.length;i++)
            RealSum+=i;
        int MissNum=RealSum-sum+DouleRes;
        int res[]=new int[2];
        res[0]=DouleRes;
        res[1]=MissNum;
        return res;
    }
}

1119. Maximum Product of Three Numbers

Given an integer array, find three numbers whose product is maximum
and output the maximum product.

样例
Example 1:

Input: [1,2,3]
Output: 6
Example 2:

Input: [1,2,3,4]
Output: 24

public class Solution {
    /**
     * @param nums: an integer array
     * @return: the maximum product
     */
    public int maximumProduct(int[] nums) {
        // Write your code here
    Arrays.sort(nums);
        int result=1;
        if(nums.length<3) {
            for (int i = 0; i < nums.length; i++)
                result *= nums[i];
        }
        else {
            int sum=1;
            sum=nums[0]*nums[1]*nums[nums.length-1];
            for (int i = nums.length - 1; i >= nums.length - 3; i--)
                result *= nums[i];
            if(sum>result)
                result=sum;
        }
        return result;
    }
}

1126. Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to
cover the other, some nodes of the two trees are overlapped while the
others are not.

You need to merge them into a new binary tree. The merge rule is that
if two nodes overlap, then sum node values up as the new value of the
merged node. Otherwise, the NOT null node will be used as the node of
new tree.

样例
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param t1: the root of the first tree
     * @param t2: the root of the second tree
     * @return: the new binary tree after merge
     */
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        // Write your code here
        if(t1==null)return t2;
        if(t2==null)return t1;
        TreeNode t=new TreeNode( t1.val+t2.val);
        t.left=mergeTrees(t1.left,t2.left);
        t.right=mergeTrees(t1.right,t2.right);
        return t;
    }
}

1137. Construct String from Binary Tree

You need to construct a string consists of parenthesis and integers
from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair “()”.
And you need to omit all the empty parenthesis pairs that don’t affect
the one-to-one mapping relationship between the string and the
original binary tree.

Example 1:

Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4

Output: “1(2(4))(3)”

Explanation: Originallay it needs to be “1(2(4)())(3()())”,
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be “1(2(4))(3)”.
Example 2:

Input: Binary tree: [1,2,3,null,4]
1
/ \
2 3
\
4

Output: “1(2()(4))(3)”

Explanation: Almost the same as the first example,
except we can’t omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param t: the root of tree
     * @return: return a string
     */
    public String tree2str(TreeNode t) {
        // write your code here
        String res="";
        if(t==null)
            return res;
        res+=t.val;
        if(t.left==null&&t.right==null)
            return res;
        res+="("+tree2str(t.left)+")";
        if(t.right!=null)
            res+="("+tree2str(t.right)+")";
        return res;
    }
}

1138. Can Place Flowers

Suppose you have a long flowerbed in which some of the plots are
planted and some are not. However, flowers cannot be planted in
adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0
means empty and 1 means not empty), and a number n, return if n new
flowers can be planted in it without violating the no-adjacent-flowers
rule.

样例
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False

public class Solution {
    /**
     * @param flowerbed: an array
     * @param n: an Integer
     * @return: if n new flowers can be planted in it without violating the no-adjacent-flowers rule
     */
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        // Write your code here
        if(flowerbed==null)return false;
        LinkedList<Integer> list=new LinkedList<>();
        for(int i:flowerbed)
            list.add(i);
        if(flowerbed[0]==0) list.addFirst(0);
        if(flowerbed[flowerbed.length-1]==0)
            list.addLast(0);
        int cnt=0,sum=0;
        for(int i=0;i<=list.size();i++){
            if(i<list.size()&&list.get(i)==0)
                cnt++;
            else{
                sum+=(cnt-1)/2;
                cnt=0;
            }
        }
        return sum>=n;
    }
}

1143. Minimum Index Sum of Two Lists

Suppose Andy and Doris want to choose a restaurant for dinner, and
they both have a list of favorite restaurants represented by strings.

You need to help them find out their common interest with the least
list index sum. If there is a choice tie between answers, output all
of them with no order requirement. You could assume there always
exists an answer.

样例
Example 1:
Input:
[“Shogun”, “Tapioca Express”, “Burger King”, “KFC”]
[“Piatti”, “The Grill at Torrey Pines”, “Hungry Hunter Steakhouse”, “Shogun”]
Output: [“Shogun”]
Explanation: The only restaurant they both like is “Shogun”.
Example 2:
Input:
[“Shogun”, “Tapioca Express”, “Burger King”, “KFC”]
[“KFC”, “Shogun”, “Burger King”]
Output: [“Shogun”]
Explanation: The restaurant they both like and have the least index sum is “Shogun” with index sum 1 (0+1).

public class Solution {
    /**
     * @param list1: a list of strings
     * @param list2: a list of strings
     * @return: the common interest with the least list index sum
     */
    public String[] findRestaurant(String[] list1, String[] list2) {
        // Write your code here
        HashMap<String,Integer>map1=new HashMap<>();
        HashMap<String,Integer>map2=new HashMap<>();
        for(int i=0;i<list1.length;i++)
            map1.put(list1[i],i);
        for(int i=0;i<list2.length;i++)
            map2.put(list2[i],i);
        int sum=Integer.MAX_VALUE;
        if(map1.size()<map2.size()){
            HashMap<String,Integer>temp=map1;
            map1=map2;
            map2=temp;
        }
        LinkedList<String>res=new LinkedList<>();
        for(String s:map2.keySet()){
            if(map1.containsKey(s)){
                int Add=map1.get(s)+map2.get(s);
                if(sum>Add)
                    sum=Add;
            }
        }
        for(String s:map2.keySet()){
            if(map1.containsKey(s)&&(map1.get(s)+map2.get(s)==sum))
                res.addLast(s);
        }
        String[]result=res.toArray(new String[]{});
        return result;
    }
}

1347. 尾随零

给定一个整数n,返回n!(n的阶乘)的尾随零的个数。

public class Solution {
    /**
     * @param n: a integer
     * @return: return a integer
     */
    int count=0;
    public int trailingZeroes(int n){
        while (n!=0){
            count+=n/5;
            n/=5;
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/mikeoperfect/article/details/80820605