LeetCode算法题1-10
来源:互联网 发布:越南经济发展现状知乎 编辑:程序博客网 时间:2024/06/01 09:26
1.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].
解决:
问题是要从数组中找到两个数据,使得两数之和等于目标值,输出该两数的下标(从0开始)。显而易见,这里最简单的是O(n^2)的时间复杂度的解决办法。public static int[] twoSum(int[] nums, int target) { int[] answer = new int[2]; A:for (int i = 0; i < nums.length; ++i){ answer[0] = i; int b = target - nums[i]; for (int j = i + 1; j < nums.length; ++j){ if (nums[j] == b){ answer[1] = j; break A; } } } return answer;}考虑O(n)的算法,可以使用map使得查找的复杂度降为O(1)。public int[] twoSum(int[] nums, int target) { int[] answer = new int[2]; 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 b = target - nums[i]; if (map.containsKey(b) && i != map.get(b)) return new int[]{i, map.get(b)}; } return answer;}
2.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; } * } */class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; //把相加后的结果存放于链表1,pre1是用于最后有进位时在其后new新结点 ListNode ret = l1; ListNode pre1 = new ListNode(0); pre1.next = l1; int flag = 0; while (l1 != null && l2 != null) { l1.val = l1.val + l2.val + flag; flag = l1.val / 10; l1.val = l1.val % 10; pre1 = l1; l1 = l1.next; l2 = l2.next; } //如果链表2有剩余,接到链表1的后面 if (l2 != null) { pre1.next = l2; l1 = l2; } while (l1 != null) { l1.val += flag; flag = l1.val / 10; l1.val = l1.val % 10; pre1 = l1; l1 = l1.next; } if (flag > 0) { ListNode node = new ListNode(1); pre1.next = node; } return ret; } }
3.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.
//时间复杂度o(n*n) public int lengthOfLongestSubstring(String s) { if(null==s||s.length()==0){ return 0; } int max=0; for(int i=0;i<s.length();i++){ StringBuilder sb=new StringBuilder(); for(int j=i;j<s.length();j++){ if(sb.toString().contains(String.valueOf(s.charAt(j)))){ break; }else { sb.append(s.charAt(j)); if(sb.length()>max){ max=sb.length(); } } } } return max; } //时间复杂度o(n) public int lengthOfLongestSubstring(String s) { if(null==s||s.length()==0){ return 0; } HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int max=0; for (int i=0, j=0; i<s.length(); ++i){ if (map.containsKey(s.charAt(i))){ j = Math.max(j,map.get(s.charAt(i))+1); } map.put(s.charAt(i),i); max = Math.max(max,i-j+1); } return max; }}
4.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
public double findMedianSortedArrays(int[] A, int[] B) { int m = A.length, n = B.length; int l = (m + n + 1) / 2; int r = (m + n + 2) / 2; return (getkth(A, 0, B, 0, l) + getkth(A, 0, B, 0, r)) / 2.0; }public double getkth(int[] A, int aStart, int[] B, int bStart, int k) { if (aStart > A.length - 1) return B[bStart + k - 1]; if (bStart > B.length - 1) return A[aStart + k - 1]; if (k == 1) return Math.min(A[aStart], B[bStart]); int aMid = Integer.MAX_VALUE, bMid = Integer.MAX_VALUE; if (aStart + k/2 - 1 < A.length) aMid = A[aStart + k/2 - 1]; if (bStart + k/2 - 1 < B.length) bMid = B[bStart + k/2 - 1]; if (aMid < bMid) return getkth(A, aStart + k/2, B, bStart, k - k/2);// Check: aRight + bLeft else return getkth(A, aStart, B, bStart + k/2, k - k/2);// Check: bRight + aLeft}
- Longest Palindromic Substring
/** * * @param Input: "babad" Output: "bab" Note: "aba" is also a valid answer. * @return String * 思想:中心扩展法 */ private int lo; private int maxLen; public String longestPalindrome(String s) { int len=s.length(); if(len<2){ return s; } for(int i=0;i<len-1;i++){ extendPalindrome(s, i, i);//奇数扩展 extendPalindrome(s,i,i+1);//偶数扩展 } return s.substring(lo,maxLen+lo); } public void extendPalindrome(String s,int j,int k){ while (j>=0&&k<s.length()&&s.charAt(j)==s.charAt(k)){ j--; k++; } if(maxLen<k-j-1){ lo=j+1; maxLen=k-j-1; } }
- ZigZag Conversion
/** * 通过创建numRows 个StringBuffer 进行拼接 * @param 6.ZigZag Conversion convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR" * @param s ,numRows * @return string */ public String convert(String s, int numRows) { char[] c=s.toCharArray(); int len=s.length(); StringBuilder[] sb=new StringBuilder[numRows]; for(int i=0;i<numRows;i++){ sb[i]=new StringBuilder(); } int i=0; while (i<len){ for(int idx=0;idx<numRows&&i<len;idx++){ sb[idx].append(c[i++]); }//垂直方向 for(int idx=numRows-2;idx>=1&&i<len;idx--){ sb[idx].append(c[i++]); }//斜线方向 } for(int idx=1;idx<sb.length;idx++){ sb[0].append(sb[idx]); } return sb[0].toString(); }}
7.Reverse 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 int reverse(int x) { int result=0; while (x!=0){ int tail=x%10; int newResult=result*10+tail; if((newResult-tail)/10!=result){ return 0; } result=newResult; x=x/10; } return result; }
8.String to Integer (atoi)
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
/** * String to Integer (atoi) * @param str * @return int */ public int myAtoi(String str) { if(str==null||str.length()==0){ return 0; } str=str.trim(); char firstChar=str.charAt(0); int sign=1; int start=0; int len=str.length(); long sum=0; if(firstChar=='+'){ sign=1; start++; }else if(firstChar=='-'){ sign=-1; start++; } for(int i=start;i<len;i++){ if(!Character.isDigit(str.charAt(i))){ return (int)sum*sign; } sum=sum*10+str.charAt(i)-'0'; if (sign == 1 && sum > Integer.MAX_VALUE) return Integer.MAX_VALUE; if (sign == -1 && (-1) * sum < Integer.MIN_VALUE) return Integer.MIN_VALUE; } return (int) sum * sign; }
- LeetCode算法题1-10
- Leetcode 算法题10
- LeetCode 算法刷题(10)
- LeetCode的算法题1:Two Sum
- Leetcode算法题(1)Two Sum
- 【LeetCode】算法题1 twoSum的归纳
- Leetcode sql算法题
- leetcode算法刷题
- LeetCode | HouseRobber 算法题
- leetcode算法第二题
- LeetCode算法题典
- leetcode算法刷题
- HappyNumber leetcode算法题
- Leetcode 算法题01
- Leetcode 算法题02
- Leetcode 算法题03
- Leetcode 算法题04
- Leetcode 算法题05
- 5分钟教你玩转 sklearn 机器学习(上)
- POJ 3525 Most Distant Point from the Sea [二分+半平面交]
- 原生json获取数据
- JDK-9的安装记录
- 百度地图集成
- LeetCode算法题1-10
- bzoj4839: [Neerc2016]Abbreviation
- android service
- 希尔排序
- HUD 1114 Piggy-Bank 存钱罐 (完全背包 动态规划DP)
- 关于北京租房,我想吐槽的一些东西
- [NOIP2017模拟]Work
- Linux system 8
- Activiti 接收任务(receivetask)