Skip to content

Commit

Permalink
315
Browse files Browse the repository at this point in the history
  • Loading branch information
RealHacker committed Jan 24, 2016
1 parent 17c7417 commit 64a517f
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 0 deletions.
10 changes: 10 additions & 0 deletions 315_count_of_smaller_numbers/README.md
@@ -0,0 +1,10 @@
This problem can be solved by sorting:

We will do insertion sort with binary search to find the place to insert, we need to record 2 things for each number:

1. C1 - The number of elements less than or equal to N when N is inserted
2. C2 - The index of N after the whole list has been sorted

`C2-C1` is the number of smaller element after N

But we need to output the counts in original sequence, this can be done by carrying the original index with the number, and finally sorting by this index.
18 changes: 18 additions & 0 deletions 315_count_of_smaller_numbers/count_of_smaller_numbers.py
@@ -0,0 +1,18 @@
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
pairs = [(num, i) for i, num in enumerate(nums)]
s = []
d = {}
for pair in pairs:
i =bisect.bisect_right(s, pair)
s.insert(i, pair)
d[pair[1]] = i
#print s
newpairs = [(j-d[pair[1]], pair[1]) for j,pair in enumerate(s)]
newpairs = sorted(newpairs, key = operator.itemgetter(1))
return [p[0] for p in newpairs]

27 changes: 27 additions & 0 deletions 315_count_of_smaller_numbers/count_of_smaller_numbers_TLE.py
@@ -0,0 +1,27 @@
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
pairs = [(i, num) for i, num in enumerate(nums)]
s = []
d = {}
for pair in pairs:
if not s:
s.append(pair)
d[pair[0]] = 0
else:
i =0
while i<len(s):
if pair[1]>=s[i][1]:
i+=1
else:
break
s.insert(i, pair)
d[pair[0]] = i
print s
newpairs = [(j-d[pair[0]], pair[0]) for j,pair in enumerate(s)]
newpairs = sorted(newpairs, key = operator.itemgetter(1))
return [p[0] for p in newpairs]

32 changes: 32 additions & 0 deletions 328_odd_even_linked_list/odd_even_linked_list.py
@@ -0,0 +1,32 @@
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
odd = oddtail = head
even =eventail = head.next
cur = even.next
i=0
while cur:
if i%2==0:
oddtail.next = cur
oddtail = cur
else:
eventail.next = cur
eventail = cur
i+=1
cur = cur.next
oddtail.next = even
eventail.next = None
return odd


0 comments on commit 64a517f

Please sign in to comment.