leetcode之top100_01_twoSsum/top100_20_ValidParentheses

本文提供了解决LeetCode上经典题目“两数之和”及“有效括号”的两种不同方法。对于“两数之和”,介绍了使用双重循环的基本解法,以及利用哈希表提高效率的优化方案;对于“有效括号”问题,则通过栈来判断字符串中的括号是否正确配对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值