mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -263,21 +263,38 @@ public:
|
||||
Java:
|
||||
|
||||
```java
|
||||
public int[] twoSum(int[] nums, int target) {
|
||||
int[] res = new int[2];
|
||||
if(nums == null || nums.length == 0){
|
||||
return res;
|
||||
}
|
||||
Map<Integer, Integer> map = new HashMap<>();
|
||||
for(int i = 0; i < nums.length; i++){
|
||||
int temp = target - nums[i];
|
||||
if(map.containsKey(temp)){
|
||||
res[1] = i;
|
||||
res[0] = map.get(temp);
|
||||
// 双指针 动态规划
|
||||
class Solution {
|
||||
public String longestPalindrome(String s) {
|
||||
if (s.length() == 0 || s.length() == 1) return s;
|
||||
int length = 1;
|
||||
int index = 0;
|
||||
boolean[][] palindrome = new boolean[s.length()][s.length()];
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
palindrome[i][i] = true;
|
||||
}
|
||||
map.put(nums[i], i);
|
||||
|
||||
for (int L = 2; L <= s.length(); L++) {
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
int j = i + L - 1;
|
||||
if (j >= s.length()) break;
|
||||
if (s.charAt(i) != s.charAt(j)) {
|
||||
palindrome[i][j] = false;
|
||||
} else {
|
||||
if (j - i < 3) {
|
||||
palindrome[i][j] = true;
|
||||
} else {
|
||||
palindrome[i][j] = palindrome[i + 1][j - 1];
|
||||
}
|
||||
}
|
||||
if (palindrome[i][j] && j - i + 1 > length) {
|
||||
length = j - i + 1;
|
||||
index = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return s.substring(index, index + length);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -118,6 +118,27 @@ class Solution {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
// 解法二
|
||||
class Solution {
|
||||
public int islandPerimeter(int[][] grid) {
|
||||
// 计算岛屿的周长
|
||||
// 方法二 : 遇到相邻的陆地总周长就-2
|
||||
int landSum = 0; // 陆地数量
|
||||
int cover = 0; // 相邻陆地数量
|
||||
for (int i = 0; i < grid.length; i++) {
|
||||
for (int j = 0; j < grid[0].length; j++) {
|
||||
if (grid[i][j] == 1) {
|
||||
landSum++;
|
||||
// 统计上面和左边的相邻陆地
|
||||
if(i - 1 >= 0 && grid[i-1][j] == 1) cover++;
|
||||
if(j - 1 >= 0 && grid[i][j-1] == 1) cover++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return landSum * 4 - cover * 2;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
|
Reference in New Issue
Block a user