#每日一题2018/3/26

昨天只刷了一道leetcode 15,故没有单开一篇

15和16道理相同,只是所问不同,从16题中我再次体会到了自身做题时的浮躁和粗糙。袖手于前方能疾书于后。

leetcode 16

爱乱初始化的毛病

class Solution {
public:
    int threeSumClosest(vector& nums, int target) {
        int length=nums.size();
		sort(nums.begin(),nums.end());
		int close=INT_MAX;
		int clostsum=0;
		for(int i=0;i0)
			{
				if(real-target

Leetcode 17 第一反应迭代遍历

看到通常做法是回溯算法,顺道学习一下

说实话没有完全理解解法,POJ见

public class Solution {
public List letterCombinations(String digits) {
        String[] table = new String[] {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        List list=new ArrayList();
        letterCombinations(list,digits,"",0,table);
        return list;
    }
    private void letterCombinations (List list, String digits, String curr, int index,String[] table) 
    {
    	if (index==digits.length()) {
             if(curr.length()!=0) list.add(curr);
             return;
         }
        String temp=table[digits.charAt(index)-'0'];
         for (int i = 0; i < temp.length(); i++) {
            String next=curr+temp.charAt(i);
            letterCombinations(list,digits,next,index+1,table);
        }
	}
}; 

LeetCode 18 

看到这个就自然想到了Magry的四合归零,以空间换时间。但显然此处条件不符

class Solution {
public:
    vector> fourSum(vector& nums, int target) {
        int length=nums.size();
        sort(nums.begin(),nums.end());
        vector > result;
        if(length<4) return result;
        for(int i=0;i0&&ii+1&&j temp(4);
        			if(nums[i]+nums[j]+nums[left]+nums[right]==target)
        			{
        				temp[0]=nums[i];
        				temp[1]=nums[j];
        				temp[2]=nums[left];
        				temp[3]=nums[right];
        				result.push_back(temp);
        				left++;
        				right--;
        				while(leftj+1&&nums[left-1]==nums[left])
        				{
        					left++;
						}
						while(leftj+1&&nums[left-1]==nums[left])
        				{
        					left++;
						}
					}
					else if(nums[i]+nums[j]+nums[left]+nums[right]>target)
					{
						right--;
                        while(left

Leetcode 19

用上了单链表找倒数第N个元素的通用方法:快慢指针

注意要特别判断删除头指针的操作,此处运用了比较取巧的操作:设置一个结点,使其成为头指针的前一个结点。这样简化操作。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
    	ListNode start = new ListNode(0);
    	start->next=head;
        ListNode *fir=start->next,*sec=start->next,*temp;
        int count=1;
        for(int i=0;sec!=NULL;i++)
        {
        	count++;
        	if(inext;
			}
			else
			{
				sec=sec->next;
				fir=fir->next;
			}
		}
		fir->next=fir->next->next;
		return start->next;
    }
};


你可能感兴趣的:(每日一题)