算法总结案例
本文分享力扣算法学习,每日一算法
力扣官网链接链接
1.两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
- 我的答案
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result= new int[2];
int length= nums.length;
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if (nums[i]+nums[j] == target){
return new int[]{i, j};
}
}
}
return new int[0];
}
}
- 官网答案
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
*总结
通过空间换时间,通过使用哈希数据结构,把数与索引值放到hash里面进判断
2.回文数
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。
示例 1:
输入:x = 121
输出:true
示例 2:
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入:x = 10
输出:false
解释:从右向左读, 为 01 。因此它不是一个回文数。
- 答案
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber =0;
while(x>revertedNumber){
revertedNumber = revertedNumber * 10 + x % 10;
x/=10;
}
return x == revertedNumber || x == revertedNumber / 10;
}
}
- 总结
充分利用了取模,除法运算
3.罗马数字转整数
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如, 罗马数字 2 写做 II ,即为两个并列的 1 。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
给定一个罗马数字,将其转换成整数
- 答案
class Solution {
Map<Character, Integer> symbolValues = new HashMap<Character, Integer>() {{
put('I', 1);
put('V', 5);
put('X', 10);
put('L', 50);
put('C', 100);
put('D', 500);
put('M', 1000);
}};
public int romanToInt(String s) {
int ans = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
int value = symbolValues.get(s.charAt(i));
if (i < n - 1 && value < symbolValues.get(s.charAt(i + 1))) {
ans -= value;
} else {
ans += value;
}
}
return ans;
}
}
- 总结
罗马数字,一般是右边比左边大,进行加法运算,但有个例,左边比右边小,直接减
4.最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
示例 2:
输入:strs = [“dog”,“racecar”,“car”]
输出:“”
解释:输入不存在公共前缀。
- 我的答案
class Solution {
public static String longestCommonPrefix(String[] strs) {
String result="";
if(strs.length==1){
result = strs[0];
return result;
}
for(int i=0;i<strs[0].length();i++){
char c=strs[0].charAt(i);
for(int j=1;j<strs.length;j++){
if(strs[j].length()>i){
char b=strs[j].charAt(i);
if(c==b && j==strs.length-1){
result=result+c;
}else if(c==b){
continue;
}else{
return result;
}
}else{
return result;
}
}
}
return result;
}
}
- 官方答案
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
int length = strs[0].length();
int count = strs.length;
for (int i = 0; i < length; i++) {
char c = strs[0].charAt(i);
for (int j = 1; j < count; j++) {
if (i == strs[j].length() || strs[j].charAt(i) != c) {
return strs[0].substring(0, i);
}
}
}
return strs[0];
}
}
5.有效的括号
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = “()”
输出:true
示例 2:
输入:s = “()[]{}”
输出:true
示例 3:
输入:s = “(]”
输出:false
- 答案
class Solution {
public boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {
return false;
}
Map<Character, Character> pairs = new HashMap<Character, Character>() {{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
}
- 总结
这里巧妙用到了栈的数据结构,先进后出
stack.pop 从栈顶移除元素
stack.push从栈顶添加元素
stack.peek从栈顶获取元素
例如 :({})、()、{}
先把左元素放入栈中,然后右元素进行对比,有则从栈顶移除,没有,说明不对称
6.合并两个有序链表
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
} else if (l2 == null) {
return l1;
} else if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
- 总结
运用递归算法进行层层比较,赋值
7.删除有序数组中的重复项
- 答案
class Solution {
public int removeDuplicates(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int fast = 1, slow = 1;
while (fast < n) {
if (nums[fast] != nums[fast - 1]) {
nums[slow] = nums[fast];
++slow;
}
++fast;
}
return slow;
}
}
- 总结
这个需要认真读懂题意,需要断言判断nums,取重后,按照返回结果循环遍历取值,说明nums 里面值进行前后比较,移动覆盖
8.移除元素
- 我的答案
class Solution {
public int removeElement(int[] nums, int val) {
int len=nums.length;
int mid;
int result=0;
for(int i=0;i<len;i++){
if(nums[i]==val){
mid=nums[i];
for(int j=i+1;j<len;j++){
if(nums[j] != val){
nums[i]=nums[j];
nums[j]=mid;
result++;
break;
}
}
}else{
result++;
}
}
return result;
}
}
- 官方答案
class Solution {
public int removeElement(int[] nums, int val) {
int n = nums.length;
int left = 0;
for (int right = 0; right < n; right++) {
if (nums[right] != val) {
nums[left] = nums[right];
left++;
}
}
return left;
}
}
- 总结
我的方法就比较麻烦了,我刚开始思路是,与val相等,就进行替换,那么应该替换到那一个呢,那就是与val不相等的值。我当时也想,可不可以记录替换的位置,进行下一次不相等的值进行替换,这个思路就截止到这,官方的答案确实这个思路进行实现的,不是相邻位置替换,是对记录位置进行替换
9.找出字符串中第一个匹配项的下标
- 暴力解法
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
for (int i = 0; i + m <= n; i++) {
boolean flag = true;
for (int j = 0; j < m; j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
return i;
}
}
return -1;
}
}
- 官方答案
运用kmp算法
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
if (m == 0) {
return 0;
}
int[] pi = new int[m];
//获取next数组,里面的值为前缀与后缀相等部分
//1.先初始化数组 2.前后缀不相等,向前移动一位,3.前后缀相等,j++,
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
j = pi[j - 1];
}
if (needle.charAt(i) == needle.charAt(j)) {
j++;
}
pi[i] = j;
}
//同理
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
j = pi[j - 1];
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}
}
10.搜索插入位置
- 官方答案
class Solution {
public int searchInsert(int[] nums, int target) {
int n = nums.length;
int left = 0, right = n - 1, ans = n;
while (left <= right) {
int mid = ((right - left) >> 1) + left;
if (target <= nums[mid]) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return ans;
}
}
- 总结
使用二分法 进行求解, >> 1 表示右移1位,相等于 /2
11.最后一个单词的长度
- 答案
class Solution {
public int lengthOfLastWord(String s) {
int index = s.length() - 1;
while (s.charAt(index) == ' ') {
index--;
}
int wordLength = 0;
while (index >= 0 && s.charAt(index) != ' ') {
wordLength++;
index--;
}
return wordLength;
}
}
- 总结
反向计算
12.加一
- 答案
class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
for (int i = n - 1; i >= 0; --i) {
if (digits[i] != 9) {
++digits[i];
for (int j = i + 1; j < n; ++j) {
digits[j] = 0;
}
return digits;
}
}
// digits 中所有的元素均为 9
int[] ans = new int[n + 1];
ans[0] = 1;
return ans;
}
}
- 总结
倒序,找出第一个不为9的数,进行+1,全为9,才进行创建新的数组、
13 爬楼梯
- 答案
class Solution {
public int climbStairs(int n) {
int p = 0, q = 0, r = 1;
for (int i = 1; i <= n; ++i) {
p = q;
q = r;
r = p + q;
}
return r;
}
}
- 总结
dp【i】=dp[i-1]+dp[i-2]
14 二叉树中序排列
- 答案
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
inorder(root, res);
return res;
}
public void inorder(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
}
15 删除排序链表中的重复元素
- 我的解法
class Solution {
public ListNode deleteDuplicates(ListNode head) {
repeat(head);
return head;
}
public void repeat(ListNode head){
if(head==null || head.next ==null){
return ;
}
if(head.val==head.next.val){
head.next=head.next.next;
repeat(head);
}else{
repeat(head.next);
}
}
}
16 菲波那契数列
菲波那契数列 :0 1 1 2 3 5 8 …
求 n项 是多少
代码实现
运用了动态规划,空间换时间
#include <iostream>
#include <vector>
int fibonacci(int n) {
if (n <= 1) {
return n;
}
std::vector<int> dp(n + 1);
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
int main() {
int n = 10; // 求第 n 项
int result = fibonacci(n);
std::cout << "第 " << n << " 项的菲波那契数列值为:" << result << std::endl;
return 0;
}