Leetcode Journey

数组按出现频次从大到小排序

http://www.geeksforgeeks.org/amazon-interview-set-21/

#include <stdio.h>

typedef struct
{
int id;
int count;
}item;

void sort(int a[], int n)
{
item temp[n];
memset(temp,0,sizeof(temp));

int index=0;
for(int i=0;i<n;i++)
{
int count=1;
temp[index].id=a[i];
while(temp[index].id==a[i+count])
{

count++;
}
temp[index].count=count;

printf("id:%d,count:%d\n",temp[index].id,temp[index].count);
index++;
i+=count-1;
}

int j=0;
int k=0;
while(temp[j].count!=0) //should usd stable sort
{
int k=j+1;
while(temp[k].count!=0)
{
if(temp[k].count>temp[j].count)
{
item var=temp[j];
temp[j]=temp[k];
temp[k]=var;
}
k+=1;
}
printf("id:%d,count:%d\n",temp[j].id,temp[j].count);

j+=1;
}
printf("ddddd\n");

int m=0;
while(temp[m].count!=0)
{
while(temp[m].count--)
{
printf("%d",temp[m].id);
}
m+=1;
}
}
int main(void) {
// your code goes here

int a[]={65,65,1,1,1,2,2,0,9,9,9,9};
sort(a,12);
return 0;
}

344. Reverse String

Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.

void inverse(int start, int end, char *p)
{
char temp;
if(p)
{
temp=p[start];
p[start]=p[end];
p[end]=temp;
return;
}
else
{
return;
}
}

char* reverseString(char* s)
{
int length=strlen(s);
printf("%d\n",length);
if(!s)
{
return NULL;
}

int start;
int end;

start=0;
end=length-1;

while(start<end)
{
//char *p=s+start;
inverse(start,end,s); //这边犯了个错误,将 p作为参数传入,p地址偏移后,end的计数就应该也要减1,正确应该直接将S传入
//printf("%c",s[start]);
start++;
end--;
//printf("%s\n",s);
}
return s;
}

136. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

int singleNumber(int* nums, int numsSize)
{
//a^a=0,a^b=b^a, 0^a=a;
//利用异或操作的特性 int a=0;
for(int i=0;i<numsSize;i++)
{
a=a^nums[i];
}

return a;
}

389. Find the Difference

Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.

void fast_sort(int start, int end, char *array)
{
if(start>=end)
return;

int pivot=array[start];
int i=start;
int j=end;

while(i<j)
{
while(i<j && array[j]>=pivot)
{
j--;
}

array[i]=array[j];

while(i<j && array[i]<=pivot)
{
i++;
}

array[j]=array[i];
}

array[i]=pivot;

fast_sort(start,i-1, array);
fast_sort(i+1,end,array);
}

char findTheDifference(char* s, char* t)
{
int len1=strlen(s);
int len2=strlen(t);

char *comp1=(char *)malloc(sizeof(char)*strlen(t));
//char *comp2=(char *)malloc(sizeof(char)*strlen(t));

memcpy(comp1,t,len2);

printf("len t:%d,len s:%d\n",strlen(t),strlen(s));
printf("%s\n",s);
printf("%s\n",t);

fast_sort(0,len1-1,s);
fast_sort(0,len2-1,t);

printf("%s\n",s);
printf("%s\n",t);

for(int i=0;i<len1;i++)
{
if(s[i]!=t[i])
{
if(t[i]==comp1[len2-1]);
return s[i];
}
}
char ret=t[len2-1];
//free(comp1);

//free(comp2);
printf("%c",ret);
return ret;
}

Ransom note

看成了KMP 匹配算法,这边实现了下

void get_next(char *key,int *next)
{ next[0]=0;
int i=0;
int j=-1;
while(i<strlen(key))
{
if(j==-1 || key[i]==key[j])
{
++i;
++j;
next[i]=j;
}
else
{
j=next[j]-1;
}
}
}

bool canConstruct(char* ransomNote, char* magazine)
{
int len=strlen(ransomNote);
int len_mag=strlen(magazine);
int *next=(int *)malloc(sizeof(int)*len);
get_next(ransomNote, next);
for(int i=0;i<len;i++)
{ printf("%d\t",next[i]); }

printf("\n len:%d,len_mag:%d\n",len,len_mag);
int i=0;
int j=0;
while(i<len_mag && j<len)
{
printf("i:%d,j:%d\n",i,j);
if(magazine[i]==ransomNote[j] )
{ i++; j++; }
else
{
if(j==0)
{ i++; }
else
{ j=next[j]; }
}
if(j==len)
{ printf("true\n"); return true; }
}
printf("false\n");
return false;
}

真正的解法:

349 Intersection of Two ArraysHash 表的解法

#define HASHSIZE 1000

/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize)
{
int *ret;
int hash[HASHSIZE] = { 0 };

if (!nums1 || !nums2)
return NULL;

*returnSize = 0;
ret = calloc(MAX(nums1Size, nums2Size), sizeof(*nums1));

for (int i = 0; i < nums1Size; ++i)
hash[nums1[i]] = 1;

for (int i = 0; i < nums2Size; ++i)
if (hash[nums2[i]] == 1)
hash[nums2[i]] = 2;

for (int i = 0; i < HASHSIZE; ++i)
if (hash[i] == 2)
ret[(*returnSize)++] = i;

return ret;
}`

169 Majority ElementAll

Solutions
:https://discuss.leetcode.com/topic/17446/6-suggested-solutions-in-c-with-explanations- Hash table:- Moore voting algorithm** introduce to moore voting algorithm**<http://www.cs.utexas.edu/~moore/best
ideas/mjrty/index.html>

int majorityElement(int* nums, int numsSize)
{
int count=0;
int retval=0;
for(int i=0;i<numsSize;i++)
{
if(count==0)
{
retval=nums[i];
count++;
}
else
{
if(retval==nums[i])
{
count++;
}
else
{
count--;
}
}
}
return retval;
}
Bit manipulationint majorityElement(int* nums, int numsSize)
{
int mask=0x00000001;
int retval;
for(int i=0;i<32;i++)
{
int count=0;
for(int j=0;j<numsSize;j++)
{
if(mask&nums[j])
{
count++;
}
}
if(count>numsSize/2)
{
retval|=mask;
}
mask<<=1;
}
}

350. Intersection of Two Arrays IIelegant

solution of python:

def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dict1 = dict()
for i in nums1:
if i not in dict1:
dict1[i] = 1
else:
dict1[i] += 1
ret = []
for i in nums2:
if i in dict1 and dict1[i]>0:
ret.append(i)
dict1[i] -= 1
return ret

401. Binary Watch

from collections import defaultdict

class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
minute=defaultdict(lambda:list())
hour=defaultdict(lambda:list())

for i in range(60):
binary='{0:b}'.format(i)
minute[binary.count('1')].append(i)

for j in range(12):
binary='{0:b}'.format(j)
hour[binary.count('1')].append(j)

ret=list()
for i in range(num+1):
for j in hour[i]:
for k in minute[num-i]:
if len(str(k))<2:
ret.append(str(j)+':0'+str(k))
else:
ret.append(str(j)+':'+str(k))

return ret

566. Reshape the Matrix

class Solution(object):

def matrixReshape(self, nums, r, c):
flat = sum(nums, [])
if len(flat) != r * c:
return nums

print [iter(flat)]
print flat

#print *([iter(flat)]*c)
tuples = zip(*([iter(flat)] * c))
return map(list, tuples)

557 Reverse Words in a String III

my solution:

class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
lista=list()
s1=""
ret=""
for x in s:
if x!=' ':
s1+=x

else:
lista.append(s1)
s1=""

lista.append(s1) // append last string

print lista
for x in lista:
x=x[::-1]

ret+=x+' '

ret=ret[:-1] //delete last space, attention, last index is -1,and not included
return ret

better solution:
use python split function:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
                return " ".join(map(lamada x: x[ : :-1], s.split()))
                // note: " ".join will insert a space into join list element

62 unique path

  • By matrix:
	class Solution:
	def uniquePaths(self, m, n):
		 """
		:type m: int
		:type n: int
		:rtype: int
		 """
		 matrix = [[0 for j in range(n)] for i in range(m)]
		 matrix[0][0] = 1
		 for i in range(m):
			 for j in range(n):
				 if j > 0:
				 matrix[i][j] += matrix[i][j - 1]
				 if i > 0:
				 matrix[i][j] += matrix[i - 1][j]
		 return matrix[-1][-1]
  • By hashmap:
class Solution:
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        dic = {(0, 0): 1}
        i, j = 0 , 1 
        while i < m:
            add1 = dic[(i, j - 1)] if j > 0 else 0
            add2 = dic[(i - 1, j)] if i > 0 else 0
            dic[(i, j)] = add1 + add2
            if j + 1 < n: j += 1
            else: i, j = i + 1, 0
        return dic[(m - 1, n - 1)] 

63. Unique Paths II

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        m=len(obstacleGrid)
        n=len(obstacleGrid[0])

        if obstacleGrid[0][0]==1:
            return 0

        obstacleGrid[0][0]=2

        for i in range(m):
            for j in range(n):
                if i>0 and obstacleGrid[i][j]!=1 :
                    obstacleGrid[i][j]+=obstacleGrid[i-1][j]
                    print "i=%d,j=%d, %d" %(i,j,obstacleGrid[i][j] )
                if j>0 and obstacleGrid[i][j]!=1 :
                    obstacleGrid[i][j]+=obstacleGrid[i][j-1]
                    print "xxx i=%d,j=%d, %d" %(i,j,obstacleGrid[i][j] )


        return obstacleGrid[-1][-1]/2

正确方式:

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid):
        ""
        :type obstacleGrid: List[List[int]]
        :rtype: int
        ""
        m=len(obstacleGrid)
        n=len(obstacleGrid[0])
        if obstacleGrid[0][0]==1:
            return 0
        obstacleGrid[0][0]=2
        for i in range(m):
            for j in range(n):
                if i>0 and obstacleGrid[i][j]!=1 and obstacleGrid[i-1][j]!=1:
                    obstacleGrid[i][j]+=obstacleGrid[i-1][j]
                if j>0 and obstacleGrid[i][j]!=1 and obstacleGrid[i][j-1]!=1:
                    obstacleGrid[i][j]+=obstacleGrid[i][j-1]
        return obstacleGrid[-1][-1]/2

when input is [0,1][0,0] the output will be 0,
python在进行二维数组遍历的时候,并非按照逐行后逐列的方式遍历,可能是先列后行。因此结果错误。

49. Group Anagrams

Tag: HashTable, String
我的code,超时,分析,时间复杂度应该是o(n^2),(1+n)n/2

# my solution , out of time
class Solution:
    def isAnagrams(self,a,b):
        dic1=dict()
        dic2=dict()
        for c in a:
            dic1[c]=dic1.get(c,0)+1
        for c in b:
            dic2[c]=dic2.get(c,0)+1
            
        return dic1==dic2
    def groupAnagrams(self, strs):
        """
        #:type strs: List[str]
        #:rtype: List[List[str]]
        """
        li=list()
        ret=list()
        
        for char in strs:
            a=bool()
            for i in range(len(ret)):
                if self.isAnagrams(char,ret[i][0]):
                    ret[i].append(char)
                    a=True
            if a==False:
                li.append(char)
                ret.append(li)
                li=[]
            a=False             
        return ret
                
        """
        for i in len(strs):
            j=i+1
            while j<len(strs):
                if isAnagrams(strs[i],strs[j]):
                    li.add(strs[j])
            
            if li!=[]:
                li.add(str[i])
            ret.add(li)
            li=[]
        return ret    
        """    

""""

从discuss中看到的,通用的做法是对元素先进行排序,然后通过hashmap进行索引,此种方法的复杂度与排序算法相关,python和C++ 都提供了O(NlogN)的复杂度的排序函数。

class Solution:
    def convert(self,s):
        lis=list(s)
        lis.sort()
        print(lis)
        return ''.join(lis)
    def groupAnagrams(self, strs):
        dic={}
        for str in strs:
            cons=self.convert(str)
            if cons in dic:
                dic[cons].append(str)
            else:
                dic[cons]=[str]
        return list(dic.values())
# solution 2
class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        groups = {}
        for s in strs:
            key = ''.join(sorted([c for c in s]))
            if key in groups:
                groups[key].append(s)
            else:
                groups[key] = [s]
        return list(groups.values())
# solution 3
class Solution:
    def groupAnagrams(self, strs):
        dic = collections.defaultdict(list)
        for s in strs: dic["".join(sorted(s))].append(s)
        return list(dic.values())        
        

python3 速度最快的解决方案

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        d = {}
        for s in strs:
            ss = ''.join(sorted(s))
            if ss not in d:
                d[ss] = [s]
            else:
                d[ss].append(s)
        ans = []
        for key in d:
            ans.append(d[key])
        return ans

367. Valid Perfect Square

class Solution:
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        left=0
        right=num
        while left<right:
            mid=left+(right-left)//2
            if mid **2==num:
                return True
            elif mid**2<num:
                left=mid+1
            else: 
                right=mid
        
        if left==right and left **2==num:
            return True
        
        return False        

solution from discussion

Solving with Bitwise trick.
    def BitwiseTrick(self, num):
       root = 0
       bit = 1 << 15
       
       while bit > 0 :
           root |= bit
           if root > num // root:    
               root ^= bit                
           bit >>= 1        
       return root * root == num
Using Newton's Method
    def NewtonMethod(self, num):
        r = num
        while r*r > num:
            r = (r + num/r) // 2
        return r*r == num
Math Trick for Square number is 1+3+5+ ... +(2n-1)
    def Math(self, num):
        i = 1
        while (num>0):
            num -= i
            i += 2       
        return num == 0
Binary Search Method
    def BinarySearch(self, num):
        left = 0
        right = num
        
        while left <= right:
            mid = left + (right-left)//2
            if  mid ** 2 == num:
                return True
            elif mid ** 2 > num:
                right = mid -1
            else:
                left = mid +1
        return False
Linear Method (Naive) - For comparison
    def Linear(self, num):
        i = 1
        while i ** 2 <= num:
            if i ** 2 == num:
                return True
            else:
                i += 1
        return False
I test these five methods with for i in range(100000): function(i), and get results as below.

Time for Bitwise's Method : 0.45249104499816895
Time for Newton's Method : 0.3492701053619385
Time for Math's Method : 2.641957998275757
Time for Binary Search's Method : 1.5031492710113525
Time for Linear's Method : 17.613927125930786

6. ZigZag Conversionf

for easy understanding

/*n=numRows
Δ=2n-2    1                           2n-1                         4n-3
Δ=        2                     2n-2  2n                    4n-4   4n-2
Δ=        3               2n-3        2n+1              4n-5       .
Δ=        .           .               .               .            .
Δ=        .       n+2                 .           3n               .
Δ=        n-1 n+1                     3n-3    3n-1                 5n-5
Δ=2n-2    n                           3n-2                         5n-4
*/
class Solution {
public:
    string convert(string s, int numRows) {
        string result="";
        if(numRows==1)
			return s;
        int step1,step2;
        int len=s.size();
        for(int i=0;i<numRows;++i){
            step1=(numRows-i-1)*2;
            step2=(i)*2;
            int pos=i;
            if(pos<len)
                result+=s.at(pos);
            while(1){
                pos+=step1;
                if(pos>=len)
                    break;
				if(step1)
					result+=s.at(pos);
                pos+=step2;
                if(pos>=len)
                    break;
				if(step2)
					result+=s.at(pos);
            }
        }
        return result;
    }
};

112 path sum

my solution:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    count=0
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        self.count=self.count+1
        if root==None and sum==0:
            if self.count==1:
                return False
            else:
                return True
        
        if root==None and sum!=0:
            return False
        if root!=None:
            return  self.hasPathSum(root.left,sum-root.val) or  self.hasPathSum(root.right,sum-root.val)

final solution:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if root==None:
            return False

        if root.val==sum and root.left==None and root.right==None:
            return True
        
        return  self.hasPathSum(root.left,sum-root.val) or  self.hasPathSum(root.right,sum-root.val)

84. Largest Rectangle in Histogram

class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        heights.append(0) 
        stack = [-1]   #add -1 to stack, this is magic code for me, keep stack never be None
        ans = 0
        for i in xrange(len(heights)):
            while heights[i] < heights[stack[-1]]:
                h = heights[stack.pop()] 
                w = i - stack[-1] - 1  # should minus 1 cause stack has been poped one time
                ans = max(ans, h * w)
            stack.append(i)
        heights.pop()
        return ans   

猜你喜欢

转载自blog.csdn.net/huntershuai/article/details/80415306