【今日】Leetcode
1.用两个栈实现队列
主要知识:栈的初始化和方法
算法思路:无
class CQueue {
Deque<Integer> inStack;
Deque<Integer> outStack;
protected void conversion()
{
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
public CQueue() {
inStack = new ArrayDeque<Integer>();
outStack = new ArrayDeque<Integer>();
}
public void appendTail(int value) {
inStack.push(value);
}
public int deleteHead() {
if(outStack.isEmpty()){
if(inStack.isEmpty())
{
return -1;
}
conversion();
}
return outStack.pop();
}
}
2.三数之和
主要知识:数组,集合
算法思路:双指针,排序
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list1 = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i<nums.length; ++ i)
{
if(i>0&&nums[i]==nums[i-1])
continue;
int target = - nums[i];
int k = nums.length-1;
for(int j = i+1;j< nums.length;++j)
{
if(nums[j]==nums[j-1]&&j>i+1) continue;
while(nums[j]+nums[k]>target&&j<k)
{
k--;
}
if(j==k) break;
if(nums[j]+nums[k]==target)
{
list1.add(new ArrayList<>(Arrays.asList(nums[i],nums[j],nums[k])));
}
}
}
return list1;
}
}
3.两数之和-输入有序数组
主要知识:无
算法思路:双指针
class Solution {
public int[] twoSum(int[] numbers, int target) {
int low = 0, high = numbers.length - 1;
while (low < high) {
int sum = numbers[low] + numbers[high];
if (sum == target) {
return new int[]{low + 1, high + 1};
} else if (sum < target) {
++low;
} else {
--high;
}
}
return new int[]{-1, -1};
}
}
4.两数之和
主要知识:哈希表的初始化和使用
算法思路:不能用双指针,因为排序之后下标会乱
class Solution {
public int[] twoSum(int[] nums, int target) {
int n=nums.length;
HashMap<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for(int i=0;i<n;++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];
}
}
5.两数相加
主要知识:链表,三位运算符
算法思路:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = new ListNode(0);
ListNode cur = l3;
int carry = 0;
while(l1!=null || l2!=null){
int x = l1==null ? 0 : l1.val;
int y = l2==null ? 0 : l2.val;
int sum = x+y+carry;
carry = sum/10;
sum = sum%10;
cur.next= new ListNode(sum);
cur = cur.next;
if(l1!=null)
{
l1=l1.next;
}
if(l2!=null)
{
l2=l2.next;
}
}
if(carry>0)
{
cur.next=new ListNode(carry);
}
return l3.next;
}
}
本文介绍了LeetCode中的一些经典算法问题,包括使用两个栈实现队列、三数之和、两数之和等。通过双指针、排序和哈希表等技巧解决数组和链表问题,展示了在算法设计中的巧妙思维。同时,这些题目涵盖了数据结构的基础知识,如栈、数组、链表和哈希表的运用。
1689

被折叠的 条评论
为什么被折叠?



