1. 程式人生 > >leetcode演算法刷題-持續更新

leetcode演算法刷題-持續更新

最近,聽了同學的建議準備刷leetcode的演算法題目,提高下自己的演算法能力。

不多說,直接來題:

一.

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].
答案用java寫的:
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result=new int[2];
        for(int i=0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
                int temp=nums[i]+nums[j];
                if(temp==target){
                   result[0]=i;
                   result[1]=j; 
                }
            }
        }
        return result;
    }
}

二.

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

答案:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    boolean isC=false;
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
        ListNode finresult=new ListNode(0);
        ListNode result=finresult;
        while(l1!=null||l2!=null){
            int x=(l1!=null)? l1.val :0;
            int y=(l2!=null)? l2.val :0;
            int temp=0;
            if(isC){
                temp=x+y+1;
                isC=false;
            }
            else{
                temp=x+y;
            }
            if(temp>=10){
                isC=true;
                result.next=new ListNode(temp%10);
            }
            else{
                result.next=new ListNode(temp);
            }
            if(l1!=null&&l1.next!=null){
                l1=l1.next;
            }else{
                l1=null;
            }
            if(l2!=null&&l2.next!=null){
                l2=l2.next;
            }
            else{
                l2=null;
            }
            result=result.next;
            
        }
        if(isC){
            result.next=new ListNode(1);
        }
        return finresult.next;
    }
}
三.

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

答案用js寫的:

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
        var a=s.length;
        if(s==""){
          var answer=0;  
        }else{
          var answer=1;  
        }
        var repeylist=[];
        
        var i=1;
        var answertemp;
        var k=0;
        var is=false;
        while(i<a){
            is=false;
            var word=s.charAt(i);
            for(var j=k;j<i;j++){
                var temp=s.charAt(j);
                if(word==temp){
                    k=j+1;
                    is=true;
                    break;
                }
            } 
            if(!is){
                answertemp= i-k+1;
               if(answertemp>answer){
                   answer=answertemp;
               }
               
            }
            
            i++;
        }
      return answer;
        
};

四.

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5
這道題的難度為hard,也就是困難,主要是他要求時間複雜度了。

答案(js):

var findMedianSortedArrays = function(nums1, nums2) {
   var i=0,j=0,k=0,
   m=nums1.length,
   n=nums2.length,
   t=m+n,
   p=t%2,
   q=parseInt(t/2),
   result,
   resulttemp,
   arr=[];
   while(i<m+n){
       if(m>0&&n>0){
           if(j<m&&k<n){
               if(nums1[j]>nums2[k]){
                    arr[i]=nums2[k];
                    i++;
                    k++;
               }
               else{
                    arr[i]=nums1[j];
                    i++;
                    j++;
               }
           }else if(j<m){
                    arr[i]=nums1[j];
                    i++;
                    j++;
           }else if(k<n){
                    arr[i]=nums2[k];
                    i++;
                    k++;
           }
           
       }else if(m>0){
            arr[i]=nums1[j];
            i++;
            j++;
       }else{
            arr[i]=nums2[k];
            i++;
            k++;
       }
   }
   if(p==0){
       resulttemp=(arr[q]+arr[q-1])/2;
       result=resulttemp;
   }
   else{
      resulttemp= arr[q];
      result=resulttemp;
   }
   return result;
};

五.

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4.
答案:
var arrayPairSum = function(nums) {
    var result=0;
    var h=nums.length-1;
    var l=0;
    quicksort(nums,h,l);
    
    for(var k=0;k<nums.length;k=k+2){
        result+=nums[k];
    }
    return result;
};

var sort=function(nums,h,l){
    var key=nums[l];
    while(h>l){
        while(nums[h]>=key&&h>l){
            h--;
        }
        nums[l]=nums[h];
        while(nums[l]<key&&h>l){
            l++;
        }
        nums[h]=nums[l];
        
    }
    nums[l]=key;
    return l;
}
var quicksort=function(nums,h,l){
    if(h<=l){
        return;
    }
    var index=sort(nums,h,l);
    quicksort(nums,h,index+1);
    quicksort(nums,index-1,l);
   
}

六.

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

public class Solution {
    public int majorityElement(int[] nums) {
         int major=nums[0], count = 1;
        for(int i=1; i<nums.length;i++){
            if(count==0){
                count++;
                major=nums[i];
            }else if(major==nums[i]){
                count++;
            }else count--;
            
        }
        return major;
    }
}

七.

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ xy < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ?   ?

The above arrows point to positions where the corresponding bits are different.
答案:
/**
 * @param {number} x
 * @param {number} y
 * @return {number}
 */
var hammingDistance = function(x, y) {
    var result=0;
    var temp=x^y;
    while(temp!=0){
    temp=temp&(temp-1);
    
     result+=1;
    }
    
    
    
    return result;
};

八.

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.

Example 1:

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

Note: The merging process must start from the root nodes of both trees.

答案:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        //TreeNode result=new TreeNode(0);
        if(t1==null&&t2==null){
            
        }
        else if(t1==null){
            t1=t2;
        }
        else if(t2==null){
            t1=t1;
        }
        else{
            t1.val=t1.val+t2.val;
            t1.left=mergeTrees(t1.left,t2.left);
            t1.right=mergeTrees(t1.right,t2.right);
        }
        return t1;
    }
}
九.

There is a table World

+-----------------+------------+------------+--------------+---------------+
| name            | continent  | area       | population   | gdp           |
+-----------------+------------+------------+--------------+---------------+
| Afghanistan     | Asia       | 652230     | 25500100     | 20343000      |
| Albania         | Europe     | 28748      | 2831741      | 12960000      |
| Algeria         | Africa     | 2381741    | 37100000     | 188681000     |
| Andorra         | Europe     | 468        | 78115        | 3712000       |
| Angola          | Africa     | 1246700    | 20609294     | 100990000     |
+-----------------+------------+------------+--------------+---------------+

A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million.

Write a SQL solution to output big countries' name, population and area.

For example, according to the above table, we should output:

+--------------+-------------+--------------+
| name         | population  | area         |
+--------------+-------------+--------------+
| Afghanistan  | 25500100    | 652230       |
| Algeria      | 37100000    | 2381741      |
+--------------+-------------+--------------+
答案:
# Write your MySQL query statement below
select name,population,area
from world
where area >3000000 
or population >25000000;
十.

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).

Note:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. All the integers in the array will be in the range of [-10000, 10000].

答案:

/**
 * @param {number[]} nums
 * @return {number}
 */
var arrayPairSum = function(nums) {
    var result=0;
    var h=nums.length-1;
    var l=0;
    quicksort(nums,h,l);
    
    for(var k=0;k<nums.length;k=k+2){
        result+=nums[k];
    }
    return result;
};

var sort=function(nums,h,l){
    var key=nums[l];
    while(h>l){
        while(nums[h]>=key&&h>l){
            h--;
        }
        nums[l]=nums[h];
        while(nums[l]<key&&h>l){
            l++;
        }
        nums[h]=nums[l];
        
    }
    nums[l]=key;
    return l;
}
var quicksort=function(nums,h,l){
    if(h<=l){
        return;
    }
    var index=sort(nums,h,l);
    quicksort(nums,h,index+1);
    quicksort(nums,index-1,l);
   
}

十一.

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.

Example 1:

Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

 答案:

public class Solution {
    	 public int findComplement(int num) {
	        String bin= Integer.toBinaryString(num);
	        String bintemp="";
	        for(int i=0;i<bin.length();i++){
	            char temp= bin.charAt(i);
	            if(temp=='1'){
	            	bintemp+='0';
	            }
	            else{
	            	bintemp+='1';
	            }
	        }
	        Integer c=Integer.parseInt(bintemp,2);
	        return c;
	    }
}
十二.

Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.

For example:
| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | m   | 2500   |
| 2  | B    | f   | 1500   |
| 3  | C    | m   | 5500   |
| 4  | D    | f   | 500    |
After running your query, the above salary table should have the following rows:
| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |
 答案:
# Write your MySQL query statement below
update salary
set sex=CASE sex when "f" then "m" else "f" end 

十三.

Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.


American keyboard


Example 1:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.
答案:
public class Solution {
    public String[] findWords(String[] words) {
    	String[] result=new String[words.length];
    	int k=0;
        HashMap<Character, Integer> aHashMap=new HashMap<Character, Integer>();
        HashMap<Character, Integer> bHashMap=new HashMap<Character, Integer>();
        HashMap<Character, Integer> cHashMap=new HashMap<Character, Integer>();
        aHashMap.put('q', 1);
        aHashMap.put('w', 1);
        aHashMap.put('e', 1);
        aHashMap.put('r', 1);
        aHashMap.put('t', 1);
        aHashMap.put('y', 1);
        aHashMap.put('u', 1);
        aHashMap.put('i', 1);
        aHashMap.put('o', 1);
        aHashMap.put('p', 1);
        bHashMap.put('a', 1);
        bHashMap.put('s', 1);
        bHashMap.put('d', 1);
        bHashMap.put('f', 1);
        bHashMap.put('g', 1);
        bHashMap.put('h', 1);
        bHashMap.put('j', 1);
        bHashMap.put('k', 1);
        bHashMap.put('l', 1);
        cHashMap.put('z', 1);
        cHashMap.put('x', 1);
        cHashMap.put('c', 1);
        cHashMap.put('v', 1);
        cHashMap.put('b', 1);
        cHashMap.put('n', 1);
        cHashMap.put('m', 1);
        for(int i=0;i<words.length;i++){
        	boolean isUse=false;
        	boolean isExit=true;
        	HashMap<Character, Integer> testHashMap=new HashMap<Character, Integer>();
        	for(int j=0;j<words[i].length();j++){
        		char temp=words[i].toLowerCase().charAt(j);
        		if(!isUse){
        			if(aHashMap.get(temp)!=null){
            			testHashMap=aHashMap;
            		}
            		else if(bHashMap.get(temp)!=null){
            			testHashMap=bHashMap;
            		}
            		else if(cHashMap.get(temp)!=null){
            			testHashMap=cHashMap;
            		}
        			isUse=true;
        		}
        		if(testHashMap.get(temp)==null){
        			isExit=false;
        		}
        	}
        	if(isExit){
        		result[k]=words[i];
        		k++;
        	}
        }
        String[] finresult=new String[k];
		for(int l=0;l<k;l++){
			finresult[l]=result[l];
		}

        return finresult;
    }
}
十四.

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

答案:
/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
            var p="";
	        var result="";
	        var start=0;
	        var end;
	        for(var i=0;i<s.length;i++){
	            var temp=s.charAt(i);
	            p=temp+p;
	        }
	        for(var j=0;j<p.length;j++){
	        	if(p.charAt(j)==' '){
	        		end=j;
	        		var temp=p.substring(start, end);
	        		result=" "+temp+result;
	        		start=j+1;
	        	}
	        }
	        result=p.substring(start, p.length)+result;
	        return result;
};

十五.

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.

Example 1:

Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. 
The sister has three different kinds of candies. 

Example 2:

Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. 
The sister has two different kinds of candies, the brother has only one kind of candies. 

Note:

  1. The length of the given array is in range [2, 10,000], and will be even.
  2. The number in given array is in range [-100,000, 100,000].
答案:
/**
 * @param {number[]} candies
 * @return {number}
 */
var distributeCandies = function(candies) {
     var h=candies.length-1;
    var l=0;
    quicksort(candies,h,l);
    
    var a=candies.length;
    var i=1,sis=1;
   var temp=candies[0];
   while(i<a) {
       if(sis==a/2){
           break;
       }
       if(temp!=candies[i]){
          sis++; 
       }
       temp=candies[i];
       i++;
       
   }
   return sis;
};



var sort=function(nums,h,l){
    var key=nums[l];
    while(h>l){
        while(nums[h]>=key&&h>l){
            h--;
        }
        nums[l]=nums[h];
        while(nums[l]<key&&h>l){
            l++;
        }
        nums[h]=nums[l];
        
    }
    nums[l]=key;
    return l;
}
var quicksort=function(nums,h,l){
    if(h<=l){
        return;
    }
    var index=sort(nums,h,l);
    quicksort(nums,h,index+1);
    quicksort(nums,index-1,l);
   
}