top100第一题,是给定一个整型数组,然后给定一个target,让你求数组中两个数的和为target,然后然后返回这两数的下标索引。
import java.util.HashMap;
import java.util.Map;
public class top100_01_twoSsum {
public static int[] twoSum(int [] nums,int target){
//最简单的方法,循环判断,通过了
int a=0;
int b=0;
for ( int i=0;i<nums.length-1;i++)
for(int j=i+1;j<nums.length;j++)
{
if ((nums[i]+nums[j])==target)
{
a=i;b=j;
break;
}
}
return new int[] {a,b};
}
public static int[] twoSum1(int[] numbers, int target) {
//采用hash表存储键值对(number[i],i),然后判断target-numbers[i]是否在hash表中
int [] res=new int [2];
Map<Integer, Integer> map=new HashMap<Integer,Integer>();
for (int i=0;i<numbers.length;i++)
{
if (map.containsKey(target-numbers[i]))
{
res[0]=map.get(target-numbers[i]);
res[1]=i;
return res;
}
else {
map.put(numbers[i], i);
}
}
return res;
}
public static void main(String [] args){
int[] nums={2,3,4,8,9};
int [] arr=twoSum1(nums, 12);
for (int ii :arr)
System.out.println(ii);
}
}
top100第20题ValidParentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
import java.util.Stack;
public class top100_20_ValidParentheses {
//这个题目就像求解表达式题目一样
//利用栈去求解,当遇到左部分时,把其对应的右部分都压入栈,当遇到右部分的时候,判断是否和栈顶元素一样,是则继续,不是则False
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()){
if(c=='(')
stack.push(')');
else if (c=='[') {
stack.push(']');
}
else if (c=='{') {
stack.push('}');
}
else {
if (stack.isEmpty()||c!=stack.pop())//这里要先判断栈是否为空
return false;
}
}
if (stack.isEmpty())
return true;
return false;
}
}