Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ans=new int[2];
HashMap<Integer,Integer> map =new HashMap<>();
for(int i=0;i<nums.length;++i){
map.put(nums[i],i);
}
for(int i=0;i<nums.length;++i){
if(map.containsKey(target-nums[i])&&i!=map.get(target-nums[i]))
return new int[]{i,map.get(target-nums[i])};
}
return ans;
}
}You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode node=new ListNode(0);
if(l1==null&&l2==null)return l1;
sol(node,l1,l2);
return node;
}
public void sol(ListNode res,ListNode l1,ListNode l2){
if(l1!=null)res.val+=l1.val;
else l1=new ListNode(0);
if(l2!=null)res.val+=l2.val;
else l2=new ListNode(0);
ListNode node=new ListNode(0);
if(res.val>=10){ //进位处理
res.val=res.val-10;
node.val=1;
res.next=node;
}
if(l1.next!=null||l2.next!=null){
res.next=node;
sol(res.next,l1.next,l2.next);
}
}
}Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set=new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return ans;
}
}大概就是建立一个字符集合,由于集合的特性--相异性,emmm....很显然很适合这道题,用i和j分别标记最长串的头和尾的下标,如果每次集合没包括下一个集合,那么就继续寻找即可,同时结果为当前结果和j-i两者之间的最大值,另外,如果包括了这个字符,那么把头部重复的字符给去除出集合即可,找到最后留下的一定是最大的字符串长度。
本文通过解决LeetCode上的三道经典题目,介绍了使用Java进行算法实现的方法。涵盖了数组、链表及字符串处理等内容,展示了如何运用数据结构提高算法效率。
2115

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



