记录自己的做题过程,会不定时更新~
1. 两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target-nums[i])){
return new int[]{map.get(target-nums[i]),i};
}else
map.put(nums[i],i);
}
return null;
}
}
O(n)复杂度
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target-nums[i])){
return new int[]{map.get(target-nums[i]),i};
}else
map.put(nums[i],i);
}
return null;
}
}
2. 两数相加
双指针
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
int sum,carry=0;
while (l1 != null || l2 != null) {
int x = l1 == null ? 0 : l1.val;
int y = l2 ==null ? 0: l2.val;
sum=x+y+carry;
carry=sum/10;
sum=sum%10;
cur.next=new ListNode(sum);
cur=cur.next;
if (l1!=null) l1=l1.next;
if (l2!=null) l2=l2.next;
}
if (carry==1){
cur.next=new ListNode(carry);
}
return pre.next;
}
}
9. 回文数
class Solution {
public boolean isPalindrome(int x) {
String str = String.valueOf(x);
char[] charArray = str.toCharArray();
int i,j;
for (i = 0,j=charArray.length-1;i<=j; i++,j--) {
if (charArray[i]!=charArray[j]){
return false;
}
}
return true;
}
}
13. 罗马数字转整数
class Solution {
public int romanToInt(String s) {
int preNum = change(s.charAt(0));
int sum = 0;
//从第二个开始,与前一个比较,如果比前一个小,则把前一个加到总和中
for (int i = 1; i < s.length(); i++) {
int num = change(s.charAt(i));
if (preNum < num) {
sum -= preNum;
} else {
sum += preNum;
}
preNum = num;
}
sum+=preNum;
return sum;
}
//通过罗马文找到对应数字
public static int change(char c){
switch (c){
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default:return -1;
}
}
}
21. 合并两个有序链表
双指针:
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode pre =new ListNode(0);
ListNode cur =pre;
while (list1!=null&&list2!=null){
if (list1.val<list2.val){
cur.next=list1;
list1=list1.next;
}else {
cur.next = list2;
list2 = list2.next;
}
cur=cur.next;
}
cur.next=list1==null?list2:list1;
return pre.next;
}
}
35. 搜索插入位置
二分查找
class Solution {
public int searchInsert(int[] nums, int target) {
int min =0;
int max =nums.length;
while (min<max){
int sum =(min+max)/2;
if (target>nums[sum]){
min=sum+1;
}else {
max = sum;
}
}
return max;
}
}
70. 爬楼梯
class Solution {
public int climbStairs(int n) {
//走一个和走两个都是一种方法
int p1 =1;
int p2 =1;
int count=0;
//原理:次数=n-1个+n-2个
for (int i = 0; i <n-1; i++) {
count=p1+p2;
//再将该值赋给p1,可以理解为下下一次的n-2
p1=p2;
//将count值赋给其中一个变量,可以理解为下一次的n-1
p2=count;
}
//这里要判断n为1的情况
if (n==1){
count=1;
}
return count;
}
}
83. 删除排序链表中的重复元素
去重
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while (cur!=null&&cur.next!=null){
if (cur.val==cur.next.val){
cur.next=cur.next.next;
}else {
cur=cur.next;
}
}
return head;
}
}