记录一下练习的过程,也算是对自己的激励
数据结构
算法简介
示例
1、两数之和
分析
该题目最优的做法时间复杂度是O(n)
顺序扫描数组,对每一个数字,寻找能与其匹配的另一半数字,若找到直接返回下标,未找到则进行下一个,直至找到或数组遍历结束。
代码示例
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] resIndex = new int[2];
for (int i = 0; i < nums.length; i++) {
int m = nums[i];
for (int j = i+1; j<nums.length; j++){
int n = nums[j];
if (m+n==target){
resIndex[0] = i;
resIndex[1] = j;
break;
}
}
}
return resIndex;
}
}
2、两数相加
分析
代码示例
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
int n1 = 0,n2 = 0, carry = 0;
ListNode current = head;
while (l1 != null || l2 != null || carry != 0){
if (l1 == null){
n1 = 0;
}else {
n1 = l1.val;
l1 = l1.next;
}
if (l2 == null){
n2 = 0;
}else {
n2 = l2.val;
l2 = l2.next;
}
current.next = new ListNode((n1 + n2 + carry)%10);
current = current.next;
carry = (n1 + n2 + carry) / 10;
}
return head.next;
}
}
3、无重复字符的最长子串
分析
首先判断是不是空串,空串则直接返回0
正常输入情况下,遍历整个字符串,将每个字符用map记录下来,若在后面遍历到与前面相同的字母,则需要将left指向移动,并且判断当前的left值是否包含了重复的字符。最后返回
代码示例
class Solution {
public int lengthOfLongestSubstring(String s) {
int res = 0;
if (!"".equals(s)) {
//滑动窗口
Map<Character,Integer> map = new HashMap<>();
int left = 0, right = 0;
while (right < s.length()) {
char ch = s.charAt(right);
if (map.containsKey(ch)){
left = Math.max(map.get(ch)+1,left);
}
res = Math.max(res, right - left + 1);
map.put(ch,right);
right++;
}
}
return res;
}
}