LeetCode1-5
Leetcode1:
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.
题意:给定一个整数数组,返回两个数下标满足和等于一个特定的数;假设不存在相同的元素和得到的解只有一个;
例子:数组:[2, 7, 11,15],目标值为 9, 因为 nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
思路:方法一:通过hashmap额外的存储空间---时间复杂度和空间复杂度都是O(n)
private static int[] addSum1(int[] aa, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < aa.length; i++) {
map.put(aa[i], i);
}
for (int i = 0; i < aa.length; i++) {
int complete = target - aa[i];
// 如果map中包含差值 且不是当前的值
if (map.containsKey(complete) && map.get(complete) != i) {
return new int[]{map.get(complete), i};
}
}
return null;
}
方法二:时间复杂度高,迭代尝试
// 方法1 迭代尝试 时间复杂度比较高
private static int[] addSum(int[] aa, int target) {
for (int i = 0; i < aa.length; i++) {
for (int j = i + 1; j < aa.length; j++) {
if (aa[i] == target - aa[j]) {
return new int[]{i, j};
}
}
}
return null;
}
Leetcode 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.
例子:输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 0 -> 8
结果: 342 + 465 = 807.
题意:将链表的对应节点进行相加,计算出来的结果构成新的链表;
思路:通过新建一个链表,首节点是一个虚拟的节点,然后返回虚拟节点的后面的节点;
public static ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
ListNode listNode = new ListNode(0);
ListNode result = listNode;
ListNode p1 = l1;
ListNode p2 = l2;
int cad = 0;
while (p1 != null || p2 != null) {
int aa = (p1 == null ? 0: p1.val) +(p2 == null?0:p2.val) + cad;
listNode.next = new ListNode(aa % 10);
cad = aa / 10;
listNode = listNode.next;
if (p1 != null) {
p1 = p1.next;
}
if (p2 != null) {
p2 = p2.next;
}
}
if (cad != 0) {
listNode.next = new ListNode(cad);
} return result.next;
}
Leetcode 3 :
Given a string, find the length of the longest substring without repeating characters.
题意:给定一个字符串,找到不含重复元素的子串的最大长度;
思路:
public static int lengthOfLongestSubstring(String s) {
int k = 0;
int res = 0;
char[] array = s.toCharArray();
HashSet<Character> hashSet = new HashSet<>();
for (int i = 0; i < array.length; i++) {
if (!hashSet.contains(array[i])) {
// 如果set中不存在这个值 就将他加入 并更新结果值
hashSet.add(array[i]);
res = Math.max(res, hashSet.size());
} else {
// 如果存在 将重复元素的前面部分去掉 取重复元素的下一个
while (k < i) {
if (s.charAt(k) == array[i]) {
k++;
break;
} else {
hashSet.remove(array[k]);
k++;
}
}
}
}
return res;
} public static int lengthOfLongestSubstring1(String s) {
int length = s.length();
if (length == 0) {
return 0;
}
int[] countTable = new int[256];
Arrays.fill(countTable, -1);
int max = 1;
int start = 0;
int end = 1;
countTable[s.charAt(0)] = 0;
while (end < length) {
// Has not reached a duplicate char
if (countTable[s.charAt(end)] >= start) {
start = countTable[s.charAt(end)] + 1;
}
max = Math.max(max, end - start + 1);
countTable[s.charAt(end)] = end;
end++;
}
return max;
} public static int lengthOfLongestSubstring2(String s) {
int n = s.length(), ans = 0;
int[] index = new int[128];
for (int j = 0, i = 0; j < n; j++) {
System.out.println(s.charAt(j) + "..");
System.out.println(index[s.charAt(j)] + "....");
i = Math.max(index[s.charAt(j)], i);//返回该字符第一次重复出现的位置
System.out.println("i:"+i);
ans = Math.max(ans, j - i + 1);//返回字符的长度
index[s.charAt(j)] = j + 1;//记录该字符在字符串中的位置
}
return ans;
}
Leetcode 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)).
You may assume nums1 and nums2 cannot be both empty.
题意:在两个有序数组中,寻找中位数。要求运行时间在O(log (m+n)),假设连个数组都不同时为空;
思路:将两个数组排序成一个有序的数组,如果为偶数,去中间两个数的平均值;如果为奇数,直接去中间的数;
//O(nlogn)
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
//当两个数组都是空的时候
if (m == 0 && n == 0) {
return 0;
}
//当其中一个数组为空时
if (m == 0) {
return getMidVal(nums2, n);
}
if (n == 0) {
return getMidVal(nums1, m);
}
int[] res = new int[m + n];
int j = 0;
int k = 0;
for (int i = 0; i < res.length; i++) {
//当其中一个数组为空时 另一个还未空时
if (j == m && k != n) {
res[i] = nums2[k++];
continue;
}
if (k == n && j != m) {
res[i] = nums1[j++];
continue;
}
//当两个都没空时
if (nums1[j] < nums2[k]) {
res[i] = nums1[j];
j++;
} else {
res[i] = nums2[k];
k++;
}
}
//根据奇偶数取中位数
return getMidVal(res, m + n);
} private static double getMidVal(int[] nums2, int n) {
if (n % 2 == 0) {
return (double) (nums2[n / 2 - 1] + nums2[n / 2]) / 2;
} else {
return nums2[n / 2];
}
}
问题转换为求两个数组中第K个小的元素.
首先假设数组A和B的元素个数都大于k/2,我们比较A[k/2-1]和B[k/2-1]两个元素,这两个元素分别表示A的第k/2小的元素和B的第k/2小的元素。这两个元素比较共有三种情况:>、<和=。如果A[k/2-1]<B[k/2-1],这表示A[0]到A[k/2-1]的元素都在A和B合并之后的前k小的元素中。换句话说,A[k/2-1]不可能大于两数组合并之后的第k小值,所以我们可以将其抛弃。
当A[k/2-1]>B[k/2-1]时存在类似的结论。
当A[k/2-1]=B[k/2-1]时,我们已经找到了第k小的数,也即这个相等的元素.
- 如果A或者B为空,则直接返回B[k-1]或者A[k-1];
- 如果k为1,我们只需要返回A[0]和B[0]中的较小值;
- 如果A[k/2-1]=B[k/2-1],返回其中一个;
public class Solution {
public static double findKth(int a[],int begina,int m,int b[],int beginb,int n,int k){
if(m>n) //确保函数m<=n
return findKth(b,beginb,n,a,begina,m,k);
if(m==0)
return b[beginb+k-1];
if(k==1)
return Math.min(a[begina],b[beginb]);
int ma = Math.min(k / 2, m), mb = k - ma; //把k分成两部分
if(a[begina+ma-1]<b[beginb+mb-1]) //把a数组前面ma个元素去掉,第k小的元素不在这里
return findKth(a,begina+ma,m-ma,b,beginb,n,k-ma);
else if(a[begina+ma-1]>b[beginb+mb-1]) //把b数组前面mb个元素去掉,第k小的元素不在这里
return findKth(a,begina,m,b,beginb+mb,n-mb,k-mb);
else return a[begina+ma-1]; //相等时就是它 }
public static double findMedianSortedArrays(int A[], int B[]) {
int m=A.length;
int n=B.length;
int totalLength=m+n;
if (totalLength%2 == 1) //奇数长度
return findKth(A, 0, m, B, 0, n, totalLength/2+1);
else { //偶数长
return (findKth(A, 0, m, B, 0, n, totalLength / 2) + findKth(A, 0, m, B, 0, n, totalLength / 2 + 1)) / 2;
}
}
public static void main(String[] args){
int[] a={3};
int[] b={1,2};
double median=findMedianSortedArrays(a,b);
System.out.println(median); }
}
Leetcode 5 : 最长回文子串
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
思路 动态规划
// 动态规划
public static String findLongestPalindrome1(String s) {
if (s == null || s.length() == 0 || s.length() == 1) {
return s;
}
int len = s.length();
int start = 0;
int maxlength = 0;
boolean p[][] = new boolean[s.length()][s.length()];
// 子串长度为1和为2的初始化
for (int i = 0; i < len; i++) {
p[i][i] = true;
if (i < len - 1 && s.charAt(i) == s.charAt(i + 1)) {
p[i][i + 1] = true;
start = i;
maxlength = 2;
}
}
// 使用上述结果可以dp出子串长度为3~len -1的子串
for (int strlen = 3; strlen <= len; strlen++) {
for (int i = 0; i <= len - strlen; i++) {
int j = i + strlen - 1; // 子串结束的位置
if (p[i + 1][j - 1] && s.charAt(i) == s.charAt(j)) {
p[i][j] = true;
maxlength = strlen;
start = i;
}
}
}
if (maxlength > 0)
return s.substring(start, start + maxlength);
return new String(s.substring(0, 1));
} // 中心扩展法
public String longestPalindrome(String s) {
if (s == null || s.length() == 0 || s.length() == 1) {
return s;
}
int len = s.length();
int maxlength = 0;
int start = 0;
// 类似于aba这种情况,以i为中心向两边扩展
for (int i = 0; i < len; i++) {
int j = i - 1;
int k = i + 1;
while (j >= 0 && k < len && s.charAt(j) == s.charAt(k)) {
if (k - j + 1 > maxlength) {
maxlength = k - j + 1;
start = j;
}
j--;
k++;
}
}
// 类似于abba这种情况,以i,i+1为中心向两边扩展
for (int i = 0; i < len; i++) {
int j = i;
int k = i + 1;
while (j >= 0 && k < len && s.charAt(j) == s.charAt(k)) {
if (k - j + 1 > maxlength) {
maxlength = k - j + 1;
start = j;
}
j--;
k++;
}
}
if (maxlength > 0)
return s.substring(start, start + maxlength);
return new String(s.substring(0, 1));
} // Manacher算法
public static String findLongestPalindrome3(String s) {
if (s == null || s.length() < 1)
return s;
String str = dealWithS(s); // 处理一下s,即将给字符串s的中间加上特殊字符,这样无论对于奇数字符还是偶数字符可以做同样的处理
int[] res = new int[str.length()];
int R = 0; // 当前所能扩展的半径
int C = 0; // C位置的半径为R
int maxC = 0; // 最长的半径的位置
res[0] = 0;
for (int i = 1; i < str.length(); i++) {
int j = 2 * C - i; // i点的对称点
if (j >= 0 && res[j] < R - i) // 对称点存在且对称点的回文半径在C的回文中
{
res[i] = res[j];
} else // 否则,需要根据i点一点一点的计算
{
int k = 1;
while (R + k < str.length() && 2 * i - R - k >= 0) {
if (str.charAt(R + k) == str.charAt(2 * i - R - k))
k++;
else
break;
}
res[i] = R - i + k - 1;
if (res[i] + i > R) {
R = res[i] + i;
C = i;
}
} maxC = res[maxC] > res[i] ? maxC : i; // maxC保存的是回文半径最大的那个点的位置
}
String subStr = str.substring(maxC - res[maxC], maxC + res[maxC] + 1);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < subStr.length(); i++) {
if (subStr.charAt(i) != '#')
sb.append(subStr.charAt(i));
}
return sb.toString();
} public static String dealWithS(String s) // 将原字符串进行处理
{
StringBuffer sb = new StringBuffer();
sb.append("#");
for (int i = 0; i < s.length(); i++) {
sb.append(s.charAt(i));
sb.append("#");
}
return sb.toString();
}
LeetCode1-5的更多相关文章
- Leetcode1——两数之和 详细解析
Leetcode1--两数之和 题目分类:数组.哈希表的应用 1. 题目描述 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数 ...
- Count Complete Tree Nodes || LeetCode1
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * s ...
- LeetCode1:Two Sum
题目: Given an array of integers, find two numbers such that they add up to a specific target number. ...
- leetcode1:在数组中找2个数的和正好等于一个给定值--哈希
package java_net_test; import java.util.HashMap; import java.util.Iterator; import java.util.Map; pu ...
- LeetCode1 Two Sum
题目 :Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- leetcode-1 Two Sum 找到数组中两数字和为指定和
问题描写叙述:在一个数组(无序)中高速找出两个数字,使得两个数字之和等于一个给定的值.如果数组中肯定存在至少一组满足要求. <剑指Offer>P214(有序数组) <编程之美& ...
- Leetcode-1.两数之和
题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数 ...
- [Swift]LeetCode1 .两数之和 | Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- leetcode1:两数之和
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 实例: 给定 nums = [2, 7, 11, 15],target = ...
- leetcode1
public class Solution { public int[] TwoSum(int[] nums, int target) { ]; ; i < nums.Length; i++) ...
随机推荐
- JAVA THINGKING (二)随笔
1. 基本数据员的默认值 Boolean false Char '\u0000'(null) byte (byte)0 short (short)0 int 0 long 0L float 0.0 ...
- FluentData - 轻量级.NET ORM持久化技术解决方案
官方地址:http://fluentdata.codeplex.com/ 官方教程:http://fluentdata.codeplex.com/documentation FluentData入门 ...
- js 获取url的request参数
方法1: function getRequest(strParame) { var args = new Object(); var query = location.search.substrin ...
- Mybatis invalid comparison: java.util.Date and java.lang.String
Mybatis的实体类是java.utils.Date类型,而在Mybatis的XML文件中,使用if判断了,不需要判断是否等于空字符串这种判断,需要人真一些 相关:https://blog.csdn ...
- J201700525-hm
スケルトン 骨組み(ほねぐみ) 骨架 リソース 资源
- Linux 常用命令十六 文件权限管理
一.ls -l 各段含义 wang@wang:~/workpalce/threading$ ls -l 总用量 drwxrwxr-x wang wang 12月 : a -rw-rw-r-- wang ...
- bzoj 4568: [Scoi2016]幸运数字【树链剖分+线段树+线性基】
一眼做法,好处是好想好写坏处是常数大,容易被卡(bzoj loj 洛谷开O2 能AC,不开有90分-- 大概就是树剖之后维护线段树,在线段树的每个节点上上维护一个线性基,暴力\( 60^2 \)的合并 ...
- apicloud踩坑集锦
最近在用apicloud开发,这里录入一些踩坑的地方,从头到尾,要多尴尬有多尴尬,新入app开发,记录一些心得,和遇到的坑以及解决办法. 1,apicloud 打包的Android app ,打开fr ...
- 进击的Python【第十五章】:Web前端基础之DOM
进击的Python[第十五章]:Web前端基础之DOM 简介:文档对象模型(Document Object Model,DOM)是一种用于HTML和XML文档的编程接口.它给文档提供了一种结构化的表示 ...
- bnu oj 13288 Bi-shoe and Phi-shoe
题目链接: http://www.bnuoj.com/contest/problem_show.php?pid=13288 题目大意: 给出一个n,然后给出n个幸运数([1,m]中不能被m整除的数的数 ...