2021-04-17 两数之和 :
方法一:暴力枚举:双层for循环;
方法二:hash方法,思想:new一个hashMap,当hashMap.containsKey(target-nums[i])时,return new int[] = {i,hashMap.get(target-nums[i])} ;否则 hashMap.push(nums[i],i);
public int[]twoSum(int[] nums, int target) {
int[] arr =new int[2];
for(int i =0;i
int diff = target - nums[i];
for(int j=i+1;j
if(diff == nums[j]){
arr[0] = i;
arr[1] = j;
return arr;
}
}
}
return arr;
}
public int[]towSum1(int[] nums, int target){
HashMap hashMap =new HashMap();
for(int i =0;i
if(hashMap.containsValue(target-nums[i])){
return new int[] {hashMap.get(target-nums[i]),i};
}
hashMap.put(nums[i],i);
}
return new int[0];
}
2021-04-18 删除有序数组中的重复项 :
思想:双指针,快慢指针。当fast<n(数组长度),如果nums[fast] !=nums[fast-1], nums[slow] = nums[fast],slow++;
否则,fast++;
class Solution {
public int removeDuplicates(int[] nums) {
int n = nums.length;
int fast = 1,slow = 1;
if(n == 0){
return 0;
}
while(fast < n){
if(nums[fast] != nums[fast-1]){
nums[slow] = nums[fast];
slow ++;
}
fast++;
}
return slow;
}
}
2021-04-18 两数相加:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null,tail = null;
int carray = 0;
while(l1 != null || l2 != null){
int n1 = l1 != null? l1.val : 0;
int n2 = l2 != null ? l2.val :0;
int sum = (n1 +n2 +carray);
if(head == null){
head = tail = new ListNode(sum%10);
}else{
tail.next = new ListNode(sum%10);
tail = tail.next;
}
carray = sum/10;
if(l1 != null){
l1 = l1.next;
}
if(l2 != null){
l2 = l2.next;
}
if(carray > 0){
tail.next = new ListNode(carray);
}
}
return head;
}
}
2021-04-19最长子串 :
技巧:出现子串----滑动窗口;出现重复次数、出现次数---散列表
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
HashSet<Character> occ = new HashSet<Character>();
int rk = -1, ans = 0;
for(int i=0;i<n;i++){
if(i != 0 )
{//左指针往右移动一个
occ.remove(s.charAt(i-1));
}
while(rk+1 < n && !occ.contains(s.charAt(rk+1))){
occ.add(s.charAt(rk+1));
rk++;
}
ans = Math.max(ans,rk-i+1);
}
return ans;
}
}