leetcode 27
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
class Solution {
public int removeElement(int[] nums, int val) {
int num=0;
if(nums.length==0) return 0;
for(int i=0;i<nums.length;i++){
if(nums[i]!=val){
nums[num]=nums[i];
num++;
}
}
return num;
}
}
LeetCode 36有效的数独
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
Example 1:
Input:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: true
Example 2:
Input:
[
["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being
modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentioned rules.
- The given board contain only digits
1-9
and the character'.'
. - The given board size is always
9x9
.
class Solution {
public boolean isValidSudoku(char[][] board) {
if(board.length<9&&board[0].length<9) return false;
Set <Integer> jurge_row=new HashSet<Integer>();
Set <Integer> jurge_col=new HashSet<Integer>();
Set <Integer> jurge_squ=new HashSet<Integer>();
for(int i = 0 ; i < 9 ; i++){
jurge_row.clear(); jurge_col.clear(); jurge_squ.clear();
for(int j = 0 ; j < 9 ; j++){
char curr_row = board[i][j];
char curr_col = board[j][i];
char curr_squ = board[3*(i/3)+j/3][3*(i%3)+j%3];
if(curr_row!='.'&&jurge_row.contains(Integer.valueOf(curr_row)))
return false;
if(curr_col!='.'&&jurge_col.contains(Integer.valueOf(curr_col)))
return false;
if(curr_squ!='.'&&jurge_squ.contains(Integer.valueOf(curr_squ)))
return false;
jurge_row.add(Integer.valueOf(curr_row));
jurge_col.add(Integer.valueOf(curr_col));
jurge_squ.add(Integer.valueOf(curr_squ));
}
}
return true;
}
}
leetcode32
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())
" Output: 4 Explanation: The longest valid parentheses substring is"()()"
方法:两次遍历操作,第一次从前往后遍历,第二次从后向前遍历。 因此时间复杂度为O(n)
1.从左向右扫描,当遇到左括号时,open++,当遇到右括号时,close++
如果open==close,那么需要对最长长度max进行更新操作 max = Math.max(max , 2*open)
如果 close > open ,说明右括号个数大于左括号个数,已经不满足合法性,则重新设置open=0, close=0
2.从右向左扫描,当遇到右括号时close++,当遇到左括号时,open++
如果close==open,那么更新max即 max = Math.max(max , 2*close)
如果open>close ,说明右括号个数小于左括号个数,已经不满足合法性,则重新设置open=0 ,close =0
class Solution {
public int longestValidParentheses(String s) {
int left=0;int right=0;int ans=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(')
left++;
else
right++;
if(left == right){
ans = Math.max(ans,2*right);
}
else if(right>left)
left = right = 0;
}
left=right=0;
for(int i=s.length()-1;i>=0;i--){
if(s.charAt(i)==')')
right++;
else
left++;
if(right == left)
ans = Math.max(ans,2*left);
else if(left>right)
left = right = 0;
}
return ans;
}
}
解题思路:
1.需有一个变量start记录有效括号子串的起始下标,max表示最长有效括号子串长度,初始值均为0
2.遍历给字符串中的所有字符
2.1若当前字符s[index]为左括号'(',将当前字符下标index入栈(下标稍后有其他用处),处理下一字符
2.2若当前字符s[index]为右括号')',判断当前栈是否为空
2.2.1若栈为空,则start = index + 1,处理下一字符(当前字符右括号下标不入栈)
2.2.2若栈不为空,则出栈(由于仅左括号入栈,则出栈元素对应的字符一定为左括号,可与当前字符右括号配对),
判断栈是否为空
2.2.2.1若栈为空,则max = max(max, index-start+1)
2.2.2.2若栈不为空,则max = max(max, index-栈顶元素值)
class Solution {
public int longestValidParentheses(String s) {
int max=0;
int len=s.length();
int start=0;
Stack<Integer> stack=new Stack<Integer>();
for(int index=0;index<len;index++){
if(s.charAt(index)=='('){
stack.push(index);
}else{
if(stack.isEmpty()){
start=index+1;
continue;
}else{
stack.pop();
if(stack.isEmpty()){
max=Math.max(max,index-start+1);
}else{
max=Math.max(max,index-stack.peek());
}
}
}
}
return max;
}
}
39. Combination Sum//搞不定的循环要考虑用回溯!!!!!
Given a set of candidate numbers (candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
The same repeated number may be chosen from candidates
unlimited number of times.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
Arrays.sort(candidates);
getResult(candidates,target,0,result,new ArrayList<Integer>());
return result;
}
public void getResult(int[] can, int target,int pos, List<List<Integer>>result, List<Integer> ans){
for(int i=pos;i<can.length;i++){
if(can[i]==target){
ans.add(can[i]);
result.add(new ArrayList<Integer>(ans));
ans.remove(ans.size()-1);
}else if(can[i]<target){
ans.add(can[i]);
getResult(can,target-can[i],i,result,ans);
ans.remove(ans.size()-1);
}
}
}
}
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
getResult(candidates,target,0,result,new ArrayList<Integer>());
return result;
}
public void getResult(int[] can,int target,int pos,List<List<Integer>> result, ArrayList<Integer>ans){
if(pos>can.length||target<0) return ;
if(target==0){
result.add(new ArrayList<Integer>(ans));
return ;
}
for(int p=pos;p<can.length;p++){
ans.add(can[p]);
getResult(can,target-can[p],p,result,ans);
ans.remove(ans.size()-1);
}
}
}
40. Combination Sum II
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =[10,1,2,7,6,1,5]
, target =8
, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
Arrays.sort(candidates);
getResult(candidates,target,0,result,new ArrayList<Integer>());
return result;
}
public void getResult(int[] can, int target,int pos, List<List<Integer>>result, List<Integer> ans){
if(pos>can.length||target < 0) return ;
if(target==0){
result.add(new ArrayList<Integer>(ans));
return ;
}
for(int p=pos;p<can.length;p++){
ans.add(can[p]);
getResult(can,target-can[p],p+1,result,ans);
ans.remove(ans.size()-1);
while(p<can.length-1&&can[p]==can[p+1]) p++;
}
}
}
216. Combination Sum III
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k = 3, n = 7
Output: [[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
getResult(k,n,1,0,result,new ArrayList<Integer>());
return result;
}
public void getResult(int count,int target,int begin,int dep,List<List<Integer>> result,ArrayList<Integer>ans){
if(dep<0||target<0) return ;
if(count==dep&&target==0){
result.add(new ArrayList<Integer>(ans));
return ;
}
for(int i=begin;i<=9;i++){
ans.add(i);
getResult(count,target-i,i+1,dep+1,result,ans);
ans.remove(ans.size()-1);
}
}
}
//思路一点都不清晰。。。。
48. Rotate Image
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOTallocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
class Solution {
public void rotate(int[][] matrix) {
int []temp=new int[matrix[0].length*matrix.length];
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
temp[i*matrix[0].length+j]=matrix[i][j];
}
}
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
matrix[i][j]=temp[i+(matrix[0].length-1-j)*matrix.length];
}
}
}
}
28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
class Solution {
public int strStr(String haystack, String needle) {
int len1=haystack.length();
int len2=needle.length();
if(len2==0) return 0;
if(len1<len2) return -1;
if(len1==len2){
if(haystack.equals(needle)){
return 0;
}else{
return -1;
}
}
int begin=0;
while(len1-begin>=len2){
boolean exits=true;
for(int i=begin,j=0;i<len1&&j<len2;i++,j++){
if(haystack.charAt(i)!=needle.charAt(j)){
exits=false;
break;
}
}
if(exits)
return begin;
begin++;
}
return -1;
}
}
46. Permutations
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
47
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
ArrayList<Integer> list=new ArrayList<Integer>();
if(nums.length==0) return result;
digui(nums,result,list);
return result;
}
public static void digui(int[] nums,List<List<Integer>> result,ArrayList<Integer> list){
if(nums.length==list.size()){
result.add(new ArrayList<Integer>(list));
}else{
for(int i=0;i<nums.length;i++){
if(list.contains(nums[i])) continue;
list.add(nums[i]);
digui(nums,result,list);
list.remove(list.size()-1);
}
}
}
}
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
ArrayList<Integer> list=new ArrayList<Integer>();
if(nums.length==0) return result;
Arrays.sort(nums);
digui(nums,result,list,new int[nums.length],0);
return result;
}
public static void digui(int[] nums,List<List<Integer>> result,ArrayList<Integer> list,int[] pos,int len){
if(nums.length==len){
result.add(new ArrayList<Integer>(list));
}
for( int i = 0 ; i<nums.length;i++){
if( pos[i] == 0 ){
list.add(nums[i]);
pos[i] = 1;
digui(nums,result,list,pos,len+1);
pos[i] = 0;
list.remove(len);
while(i<nums.length-1 && nums[i] == nums[i+1]){
i++;
}
}
}
}
}
49 Group Anagrams
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
这个题。。。我怎么才能知道他是不是个单词呢
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result=new ArrayList<List<String>>();
int len=strs.length;
if(len<1) return result;
Map<String,List<String>> map=new HashMap<String,List<String>>();
String temp="";
for(int i=0;i<strs.length;i++){
temp=strs[i];
char[] c = temp.toCharArray();
Arrays.sort(c);
temp=new String(c);
if(map.containsKey(temp)){
map.get(temp).add(strs[i]);
}else{
ArrayList<String> list=new ArrayList<String>();
list.add(strs[i]);
map.put(temp,list);
}
}
for(List<String> value:map.values()){
result.add(value);
}
return result;
}
}